📄 certtools.java
字号:
ret = true; } } else if (StringUtils.equals(cert.getType(), "CVC")) { CardVerifiableCertificate cvccert = (CardVerifiableCertificate)cert; try { CVCAuthorizationTemplate templ = cvccert.getCVCertificate().getCertificateBody().getAuthorizationTemplate(); AuthorizationRoleEnum role = templ.getAuthorizationField().getRole(); if (role.equals(AuthorizationRoleEnum.CVCA) || role.equals(AuthorizationRoleEnum.DV_D) || role.equals(AuthorizationRoleEnum.DV_F)) { ret = true; } } catch (NoSuchFieldException e) { log.error("NoSuchFieldException: ", e); } } log.debug("<isCA:" + ret); return ret; } // isSelfSigned /** * Generate a selfsigned certiicate. * * @param dn subject and issuer DN * @param validity in days * @param policyId policy string ('2.5.29.32.0') or null * @param privKey private key * @param pubKey public key * @param sigAlg signature algorithm, you can use one of the contants CATokenInfo.SIGALG_XXX * @param isCA boolean true or false * * @return X509Certificate, self signed * * @throws NoSuchAlgorithmException DOCUMENT ME! * @throws SignatureException DOCUMENT ME! * @throws InvalidKeyException DOCUMENT ME! * @throws IllegalStateException * @throws CertificateEncodingException * @throws NoSuchProviderException */ public static X509Certificate genSelfCert(String dn, long validity, String policyId, PrivateKey privKey, PublicKey pubKey, String sigAlg, boolean isCA) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, CertificateEncodingException, IllegalStateException, NoSuchProviderException { return genSelfCert(dn, validity, policyId, privKey, pubKey, sigAlg, isCA, "BC"); } public static X509Certificate genSelfCert(String dn, long validity, String policyId, PrivateKey privKey, PublicKey pubKey, String sigAlg, boolean isCA, String provider) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, CertificateEncodingException, IllegalStateException, NoSuchProviderException { int keyusage = X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign; return genSelfCertForPurpose(dn, validity, policyId, privKey, pubKey, sigAlg, isCA, keyusage, provider); } //genselfCert /** * Generate a selfsigned certiicate with possibility to specify key usage. * * @param dn subject and issuer DN * @param validity in days * @param policyId policy string ('2.5.29.32.0') or null * @param privKey private key * @param pubKey public key * @param sigAlg signature algorithm, you can use one of the contants CATokenInfo.SIGALG_XXX * @param isCA boolean true or false * @param keyusage as defined by constants in X509KeyUsage * * @return X509Certificate, self signed * * @throws NoSuchAlgorithmException DOCUMENT ME! * @throws SignatureException DOCUMENT ME! * @throws InvalidKeyException DOCUMENT ME! * @throws IllegalStateException * @throws CertificateEncodingException * @throws NoSuchProviderException */ public static X509Certificate genSelfCertForPurpose(String dn, long validity, String policyId, PrivateKey privKey, PublicKey pubKey, String sigAlg, boolean isCA, int keyusage) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, CertificateEncodingException, IllegalStateException, NoSuchProviderException { return genSelfCertForPurpose(dn, validity, policyId, privKey, pubKey, sigAlg, isCA, keyusage, "BC"); } public static X509Certificate genSelfCertForPurpose(String dn, long validity, String policyId, PrivateKey privKey, PublicKey pubKey, String sigAlg, boolean isCA, int keyusage, String provider) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, CertificateEncodingException, IllegalStateException, NoSuchProviderException { // Create self signed certificate Date firstDate = new Date(); // Set back startdate ten minutes to avoid some problems with wrongly set clocks. firstDate.setTime(firstDate.getTime() - (10 * 60 * 1000)); Date lastDate = new Date(); // validity in days = validity*24*60*60*1000 milliseconds lastDate.setTime(lastDate.getTime() + (validity * (24 * 60 * 60 * 1000))); X509V3CertificateGenerator certgen = new X509V3CertificateGenerator(); // Transform the PublicKey to be sure we have it in a format that the X509 certificate generator handles, it might be // a CVC public key that is passed as parameter PublicKey publicKey = null; if (pubKey instanceof RSAPublicKey) { RSAPublicKey rsapk = (RSAPublicKey)pubKey; RSAPublicKeySpec rSAPublicKeySpec = new RSAPublicKeySpec(rsapk.getModulus(), rsapk.getPublicExponent()); try { publicKey = KeyFactory.getInstance("RSA").generatePublic(rSAPublicKeySpec); } catch (InvalidKeySpecException e) { log.error("Error creating RSAPublicKey from spec: ", e); publicKey = pubKey; } } else { publicKey = pubKey; } // Serialnumber is random bits, where random generator is initialized with Date.getTime() when this // bean is created. byte[] serno = new byte[8]; SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed((new Date().getTime())); random.nextBytes(serno); certgen.setSerialNumber((new java.math.BigInteger(serno)).abs()); certgen.setNotBefore(firstDate); certgen.setNotAfter(lastDate); certgen.setSignatureAlgorithm(sigAlg); certgen.setSubjectDN(CertTools.stringToBcX509Name(dn)); certgen.setIssuerDN(CertTools.stringToBcX509Name(dn)); certgen.setPublicKey(publicKey); // Basic constranits is always critical and MUST be present at-least in CA-certificates. BasicConstraints bc = new BasicConstraints(isCA); certgen.addExtension(X509Extensions.BasicConstraints.getId(), true, bc); // Put critical KeyUsage in CA-certificates if (isCA == true) { X509KeyUsage ku = new X509KeyUsage(keyusage); certgen.addExtension(X509Extensions.KeyUsage.getId(), true, ku); } // Subject and Authority key identifier is always non-critical and MUST be present for certificates to verify in Mozilla. try { if (isCA == true) { SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo((ASN1Sequence) new ASN1InputStream( new ByteArrayInputStream(publicKey.getEncoded())).readObject()); SubjectKeyIdentifier ski = new SubjectKeyIdentifier(spki); SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo((ASN1Sequence) new ASN1InputStream( new ByteArrayInputStream(publicKey.getEncoded())).readObject()); AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki); certgen.addExtension(X509Extensions.SubjectKeyIdentifier.getId(), false, ski); certgen.addExtension(X509Extensions.AuthorityKeyIdentifier.getId(), false, aki); } } catch (IOException e) { // do nothing } // CertificatePolicies extension if supplied policy ID, always non-critical if (policyId != null) { PolicyInformation pi = new PolicyInformation(new DERObjectIdentifier(policyId)); DERSequence seq = new DERSequence(pi); certgen.addExtension(X509Extensions.CertificatePolicies.getId(), false, seq); } X509Certificate selfcert = certgen.generate(privKey, provider); return selfcert; } //genselfCertForPurpose /** * Get the authority key identifier from a certificate extensions * * @param cert certificate containing the extension * @return byte[] containing the authority key identifier, or null if it does not exist * @throws IOException if extension can not be parsed */ public static byte[] getAuthorityKeyId(Certificate cert) throws IOException { if (cert == null) { return null; } if (cert instanceof X509Certificate) { X509Certificate x509cert = (X509Certificate) cert; byte[] extvalue = x509cert.getExtensionValue("2.5.29.35"); if (extvalue == null) { return null; } DEROctetString oct = (DEROctetString) (new ASN1InputStream(new ByteArrayInputStream(extvalue)).readObject()); AuthorityKeyIdentifier keyId = new AuthorityKeyIdentifier((ASN1Sequence) new ASN1InputStream( new ByteArrayInputStream(oct.getOctets())).readObject()); return keyId.getKeyIdentifier(); } return null; } // getAuthorityKeyId /** * Get the subject key identifier from a certificate extensions * * @param cert certificate containing the extension * @return byte[] containing the subject key identifier, or null if it does not exist * @throws IOException if extension can not be parsed */ public static byte[] getSubjectKeyId(Certificate cert) throws IOException { if (cert == null) { return null; } if (cert instanceof X509Certificate) { X509Certificate x509cert = (X509Certificate) cert; byte[] extvalue = x509cert.getExtensionValue("2.5.29.14"); if (extvalue == null) { return null; } ASN1OctetString str = ASN1OctetString.getInstance(new ASN1InputStream(new ByteArrayInputStream(extvalue)).readObject()); SubjectKeyIdentifier keyId = SubjectKeyIdentifier.getInstance(new ASN1InputStream(new ByteArrayInputStream(str.getOctets())).readObject()); return keyId.getKeyIdentifier(); } return null; } // getSubjectKeyId /** * Get a certificate policy ID from a certificate policies extension * * @param cert certificate containing the extension * @param pos position of the policy id, if several exist, the first is as pos 0 * @return String with the certificate policy OID * @throws IOException if extension can not be parsed */ public static String getCertificatePolicyId(Certificate cert, int pos) throws IOException { String ret = null; if (cert instanceof X509Certificate) { X509Certificate x509cert = (X509Certificate) cert; byte[] extvalue = x509cert.getExtensionValue(X509Extensions.CertificatePolicies.getId()); if (extvalue == null) { return null; } DEROctetString oct = (DEROctetString) (new ASN1InputStream(new ByteArrayInputStream(extvalue)).readObject()); ASN1Sequence seq = (ASN1Sequence)new ASN1InputStream(new ByteArrayInputStream(oct.getOctets())).readObject(); // Check the size so we don't ArrayIndexOutOfBounds if (seq.size() < pos+1) { return null; } PolicyInformation pol = new PolicyInformation((ASN1Sequence)seq.getObjectAt(pos)); ret = pol.getPolicyIdentifier().getId(); } return ret; } // getCertificatePolicyId /** * Gets the Microsoft specific UPN altName. * * @param cert certificate containing the extension * @return String with the UPN name or null if the altName does not exist */ public static String getUPNAltName(Certificate cert) throws IOException, CertificateParsingException { String ret = null; if (cert instanceof X509Certificate) { X509Certificate x509cert = (X509Certificate) cert; Collection altNames = x509cert.getSubjectAlternativeNames(); if (altNames != null) { Iterator i = altNames.iterator(); while (i.hasNext()) { ASN1Sequence seq = getAltnameSequence((List)i.next()); ret = getUPNStringFromSequence(seq); if (ret != null) { break; } } } } return ret; } // getUPNAltName /** Helper method for the above method */ private static String getUPNStringFromSequence(ASN1Sequence seq) { if ( seq != null) { // First in sequence is the object identifier, that we must check DERObjectIdentifier id = DERObjectIdentifier.getInstance(seq.getObjectAt(0)); if (id.getId().equals(CertTools.UPN_OBJECTID)) { ASN1TaggedObject obj = (ASN1TaggedObject) seq.getObjectAt(1); DERUTF8String str = DERUTF8String.getInstance(obj.getObject()); return str.getString(); } } return null; } /** * Gets the Microsoft specific GUID altName, that is encoded as an octect string. * * @param cert certificate containing the extension * @return String with the hex-encoded GUID byte array or null if the altName does not exist */ public static String getGuidAltName(Certificate cert) throws IOException, CertificateParsingException { if (cert instanceof X509Certificate) { X509Certificate x509cert = (X509Certificate) cert; Collection altNames = x509cert.getSubjectAlternativeNames(); if (altNames != null) { Iterator i = altNames.iterator(); while (i.hasNext()) { ASN1Sequence seq = getAltnameSequence((List)i.next()); if ( seq != null) { // First in sequence is the object identifier, that we must check DERObjectIdentifier id = DERObjectIdentifier.getInstance(seq.getObjectAt(0)); if (id.getId().equals(CertTools.GUID_OBJECTID)) { ASN1TaggedObject obj = (ASN1TaggedObject) seq.getObjectAt(1); ASN1OctetString str = ASN1OctetString.getInstance(obj.getObject()); return new String(Hex.encode(str.getO
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -