public X509Certificate generate(String dn, KeyPair keyPair) throws CertificateException { try { Security.addProvider(new BouncyCastleProvider()); AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(algorithm); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded()); SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()); ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam); X500Name name = new X500Name(dn); Date from = new Date(); Date to = new Date(from.getTime() + days * 86400000L); BigInteger sn = new BigInteger(64, new SecureRandom()); X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder(name, sn, from, to, name, subPubKeyInfo); if (subjectAltName != null) v3CertGen.addExtension(Extension.subjectAlternativeName, false, subjectAltName); X509CertificateHolder certificateHolder = v3CertGen.build(sigGen); return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder); } catch (CertificateException ce) { throw ce; } catch (Exception e) { throw new CertificateException(e); } }
public SignerId getSignerId(X509CertSelector certSelector) { try { if (certSelector.getSubjectKeyIdentifier() != null) { return new SignerId(X500Name.getInstance(certSelector.getIssuerAsBytes()), certSelector.getSerialNumber(), ASN1OctetString.getInstance(certSelector.getSubjectKeyIdentifier()).getOctets()); } else { return new SignerId(X500Name.getInstance(certSelector.getIssuerAsBytes()), certSelector.getSerialNumber()); } } catch (IOException e) { throw new IllegalArgumentException("unable to convert issuer: " + e.getMessage()); } }
/** * Create a builder for a version 1 certificate. * * @param issuer the certificate issuer * @param serial the certificate serial number * @param notBefore the date before which the certificate is not valid * @param notAfter the date after which the certificate is not valid * @param subject the certificate subject * @param publicKeyInfo the info structure for the public key to be associated with this certificate. */ public X509v1CertificateBuilder(X500Name issuer, BigInteger serial, Date notBefore, Date notAfter, X500Name subject, SubjectPublicKeyInfo publicKeyInfo) { if (issuer == null) { throw new IllegalArgumentException("issuer must not be null"); } if (publicKeyInfo == null) { throw new IllegalArgumentException("publicKeyInfo must not be null"); } tbsGen = new V1TBSCertificateGenerator(); tbsGen.setSerialNumber(new ASN1Integer(serial)); tbsGen.setIssuer(issuer); tbsGen.setStartDate(new Time(notBefore)); tbsGen.setEndDate(new Time(notAfter)); tbsGen.setSubject(subject); tbsGen.setSubjectPublicKeyInfo(publicKeyInfo); }
public String toString(X500Name name) { StringBuffer buf = new StringBuffer(); boolean first = true; RDN[] rdns = name.getRDNs(); for (int i = 0; i < rdns.length; i++) { if (first) { first = false; } else { buf.append(','); } IETFUtils.appendRDN(buf, rdns[i], DefaultSymbols); } return buf.toString(); }
private Set loadCRLEntries() { Set entrySet = new HashSet(); Enumeration certs = c.getRevokedCertificateEnumeration(); X500Name previousCertificateIssuer = null; // the issuer while (certs.hasMoreElements()) { TBSCertList.CRLEntry entry = (TBSCertList.CRLEntry)certs.nextElement(); X509CRLEntryObject crlEntry = new X509CRLEntryObject(entry, isIndirect, previousCertificateIssuer); entrySet.add(crlEntry); if (isIndirect && entry.hasExtensions()) { Extension currentCaName = entry.getExtensions().getExtension(Extension.certificateIssuer); if (currentCaName != null) { previousCertificateIssuer = X500Name.getInstance(GeneralNames.getInstance(currentCaName.getParsedValue()).getNames()[0].getName()); } } } return entrySet; }
public boolean areEqual(X500Name name1, X500Name name2) { RDN[] rdns1 = name1.getRDNs(); RDN[] rdns2 = name2.getRDNs(); if (rdns1.length != rdns2.length) { return false; } for (int i = 0; i != rdns1.length; i++) { if (!rdnAreEqual(rdns1[i], rdns2[i])) { return false; } } return true; }
/** * Parse a {@link CertificateRequest} from an {@link InputStream}. * * @param input the {@link InputStream} to parse from. * @return a {@link CertificateRequest} object. * @throws IOException */ public static CertificateRequest parse(InputStream input) throws IOException { int numTypes = TlsUtils.readUint8(input); short[] certificateTypes = new short[numTypes]; for (int i = 0; i < numTypes; ++i) { certificateTypes[i] = TlsUtils.readUint8(input); } byte[] authorities = TlsUtils.readOpaque16(input); Vector authorityDNs = new Vector(); ByteArrayInputStream bis = new ByteArrayInputStream(authorities); while (bis.available() > 0) { byte[] dnBytes = TlsUtils.readOpaque16(bis); authorityDNs.addElement(X500Name.getInstance(ASN1Primitive.fromByteArray(dnBytes))); } return new CertificateRequest(certificateTypes, authorityDNs); }
public static X500PrivateCredential generateServerCertificate(KeyPair caKeyPair) throws NoSuchAlgorithmException, CertificateException, OperatorCreationException, CertIOException { X500Name issuerName = new X500Name("CN=bouncrca"); X500Name subjectName = new X500Name("CN=bouncr"); BigInteger serial = BigInteger.valueOf(2); long t1 = System.currentTimeMillis(); KeyPairGenerator rsa = KeyPairGenerator.getInstance("RSA"); rsa.initialize(2048, SecureRandom.getInstance("NativePRNGNonBlocking")); KeyPair kp = rsa.generateKeyPair(); System.out.println(System.currentTimeMillis() - t1); X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuerName, serial, NOT_BEFORE, NOT_AFTER, subjectName, kp.getPublic()); DERSequence subjectAlternativeNames = new DERSequence(new ASN1Encodable[] { new GeneralName(GeneralName.dNSName, "localhost"), new GeneralName(GeneralName.dNSName, "127.0.0.1") }); builder.addExtension(Extension.subjectAlternativeName, false, subjectAlternativeNames); X509Certificate cert = signCertificate(builder, caKeyPair.getPrivate()); return new X500PrivateCredential(cert, kp.getPrivate()); }
public static String getCommonName(X500Name name) { ParamUtil.requireNonNull("name", name); RDN[] rdns = name.getRDNs(ObjectIdentifiers.DN_CN); if (rdns != null && rdns.length > 0) { RDN rdn = rdns[0]; AttributeTypeAndValue atv = null; if (rdn.isMultiValued()) { for (AttributeTypeAndValue m : rdn.getTypesAndValues()) { if (m.getType().equals(ObjectIdentifiers.DN_CN)) { atv = m; break; } } } else { atv = rdn.getFirst(); } return (atv == null) ? null : rdnValueToString(atv.getValue()); } return null; }
public void addSelfSignedCertificate(String certificateAlias, String dn, String password) { try { KeyPair keys = generateKeyPair(); Calendar start = Calendar.getInstance(); Calendar expiry = Calendar.getInstance(); expiry.add(Calendar.YEAR, 1); X500Name name = new X500Name(dn); X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(name, BigInteger.ONE, start.getTime(), expiry.getTime(), name, SubjectPublicKeyInfo.getInstance(keys.getPublic().getEncoded())); ContentSigner signer = new JcaContentSignerBuilder("SHA1WithRSA").setProvider(new BouncyCastleProvider()).build(keys.getPrivate()); X509CertificateHolder holder = certificateBuilder.build(signer); Certificate cert = new JcaX509CertificateConverter().setProvider(new BouncyCastleProvider()).getCertificate(holder); Entry entry = new PrivateKeyEntry(keys.getPrivate(), new Certificate[]{ cert }); keystore.setEntry(certificateAlias, entry, new PasswordProtection(password.toCharArray())); } catch (GeneralSecurityException | OperatorCreationException ex) { throw new RuntimeException("Unable to generate self-signed certificate", ex); } }
public static X509Name getInstance( Object obj) { if (obj == null || obj instanceof X509Name) { return (X509Name)obj; } else if (obj instanceof X500Name) { return new X509Name(ASN1Sequence.getInstance(((X500Name)obj).toASN1Primitive())); } else if (obj != null) { return new X509Name(ASN1Sequence.getInstance(obj)); } return null; }
public KeyTransRecipientId getKeyTransRecipientId(X509CertSelector certSelector) { try { if (certSelector.getSubjectKeyIdentifier() != null) { return new KeyTransRecipientId(X500Name.getInstance(certSelector.getIssuerAsBytes()), certSelector.getSerialNumber(), ASN1OctetString.getInstance(certSelector.getSubjectKeyIdentifier()).getOctets()); } else { return new KeyTransRecipientId(X500Name.getInstance(certSelector.getIssuerAsBytes()), certSelector.getSerialNumber()); } } catch (IOException e) { throw new IllegalArgumentException("unable to convert issuer: " + e.getMessage()); } }
public CertificateRequest getCertificateRequest() throws IOException { short[] certificateTypes = new short[]{ClientCertificateType.rsa_sign, ClientCertificateType.dss_sign, ClientCertificateType.ecdsa_sign}; Vector serverSigAlgs = null; if (TlsUtils.isSignatureAlgorithmsExtensionAllowed(serverVersion)) { serverSigAlgs = TlsUtils.getDefaultSupportedSignatureAlgorithms(); } Vector<X500Name> certificateAuthorities = new Vector<>(); certificateAuthorities.addElement( cert.getCertificateAt(0).getSubject() ); return new CertificateRequest(certificateTypes, serverSigAlgs, certificateAuthorities); }
/** * 动态生成服务器证书,并进行CA签授 * * @param issuer 颁发机构 */ public static X509Certificate genCert(String issuer, PrivateKey caPriKey, Date caNotBefore, Date caNotAfter, PublicKey serverPubKey, String... hosts) throws Exception { /* String issuer = "C=CN, ST=GD, L=SZ, O=lee, OU=study, CN=ProxyeeRoot"; String subject = "C=CN, ST=GD, L=SZ, O=lee, OU=study, CN=" + host;*/ //根据CA证书subject来动态生成目标服务器证书的issuer和subject String subject = "C=CN, ST=GD, L=SZ, O=lee, OU=study, CN=" + hosts[0]; //doc from https://www.cryptoworkshop.com/guide/ JcaX509v3CertificateBuilder jv3Builder = new JcaX509v3CertificateBuilder(new X500Name(issuer), //issue#3 修复ElementaryOS上证书不安全问题(serialNumber为1时证书会提示不安全),避免serialNumber冲突,采用时间戳+4位随机数生成 BigInteger.valueOf(System.currentTimeMillis() + (long) (Math.random() * 10000) + 1000), caNotBefore, caNotAfter, new X500Name(subject), serverPubKey); //SAN扩展证书支持的域名,否则浏览器提示证书不安全 GeneralName[] generalNames = new GeneralName[hosts.length]; for (int i = 0; i < hosts.length; i++) { generalNames[i] = new GeneralName(GeneralName.dNSName, hosts[i]); } GeneralNames subjectAltName = new GeneralNames(generalNames); jv3Builder.addExtension(Extension.subjectAlternativeName, false, subjectAltName); //SHA256 用SHA1浏览器可能会提示证书不安全 ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(caPriKey); return new JcaX509CertificateConverter().getCertificate(jv3Builder.build(signer)); }
public int calculateHashCode(X500Name name) { int hashCodeValue = 0; RDN[] rdns = name.getRDNs(); // this needs to be order independent, like equals for (int i = 0; i != rdns.length; i++) { if (rdns[i].isMultiValued()) { AttributeTypeAndValue[] atv = rdns[i].getTypesAndValues(); for (int j = 0; j != atv.length; j++) { hashCodeValue ^= atv[j].getType().hashCode(); hashCodeValue ^= calcHashCode(atv[j].getValue()); } } else { hashCodeValue ^= rdns[i].getFirst().getType().hashCode(); hashCodeValue ^= calcHashCode(rdns[i].getFirst().getValue()); } } return hashCodeValue; }
private X500Name[] getPrincipals(GeneralName[] names) { List l = new ArrayList(names.length); for (int i = 0; i != names.length; i++) { if (names[i].getTagNo() == GeneralName.directoryName) { l.add(X500Name.getInstance(names[i].getName())); } } return (X500Name[])l.toArray(new X500Name[l.size()]); }
/** * Return the principals associated with the issuer attached to this holder * * @return an array of principals, null if no BaseCertificateID is set. */ public X500Name[] getIssuer() { if (holder.getBaseCertificateID() != null) { return getPrincipals(holder.getBaseCertificateID().getIssuer().getNames()); } return null; }
private static X500Name convertPrincipal(X500Principal issuer) { if (issuer == null) { return null; } return X500Name.getInstance(issuer.getEncoded()); }
public CertificateRequestMessageBuilder setIssuer(X500Name issuer) { if (issuer != null) { templateBuilder.setIssuer(issuer); } return this; }
public CertificateRequestMessageBuilder setSubject(X500Name subject) { if (subject != null) { templateBuilder.setSubject(subject); } return this; }
private static P12KeyGenerationResult generateIdentity(KeyPairWithSubjectPublicKeyInfo kp, KeystoreGenerationParameters params, String selfSignedCertSubject) throws Exception { Date now = new Date(); Date notBefore = new Date(now.getTime() - 10 * MIN); // 10 minutes past Date notAfter = new Date(notBefore.getTime() + 3650 * DAY); String dnStr = (selfSignedCertSubject == null) ? "CN=DUMMY" : selfSignedCertSubject; X500Name subjectDn = new X500Name(dnStr); SubjectPublicKeyInfo subjectPublicKeyInfo = kp.subjectPublicKeyInfo(); ContentSigner contentSigner = getContentSigner(kp.kypair().getPrivate()); // Generate keystore X509v3CertificateBuilder certGenerator = new X509v3CertificateBuilder(subjectDn, BigInteger.valueOf(1), notBefore, notAfter, subjectDn, subjectPublicKeyInfo); KeyAndCertPair identity = new KeyAndCertPair(certGenerator.build(contentSigner), kp.kypair().getPrivate()); KeyStore ks = KeyUtil.getKeyStore("PKCS12"); ks.load(null, params.password()); ks.setKeyEntry("main", identity.key(), params.password(), new Certificate[]{identity.jceCert()}); ByteArrayOutputStream ksStream = new ByteArrayOutputStream(); try { ks.store(ksStream, params.password()); } finally { ksStream.flush(); } P12KeyGenerationResult result = new P12KeyGenerationResult(ksStream.toByteArray()); result.setKeystoreObject(ks); return result; }
public static Certificate newCert(String parentCertFile, String keyFile, String host) { try { Date before = Date.from(Instant.now()); Date after = Date.from(Year.now().plus(3, ChronoUnit.YEARS).atDay(1).atStartOfDay(ZoneId.systemDefault()).toInstant()); X509CertificateHolder parent = readPemFromFile(parentCertFile); PEMKeyPair pemKeyPair = readPemFromFile(keyFile); KeyPair keyPair = new JcaPEMKeyConverter() .setProvider(PROVIDER) .getKeyPair(pemKeyPair); X509v3CertificateBuilder x509 = new JcaX509v3CertificateBuilder( parent.getSubject(), new BigInteger(64, new SecureRandom()), before, after, new X500Name("CN=" + host), keyPair.getPublic()); ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption") .build(keyPair.getPrivate()); JcaX509CertificateConverter x509CertificateConverter = new JcaX509CertificateConverter() .setProvider(PROVIDER); return new Certificate( keyPair, x509CertificateConverter.getCertificate(x509.build(signer)), x509CertificateConverter.getCertificate(parent)); } catch (Exception e) { throw new IllegalStateException(e); } }
public JcaCertificateRequestMessageBuilder setSubject(X500Principal subject) { if (subject != null) { setSubject(X500Name.getInstance(subject.getEncoded())); } return this; }
public JcaCertificateRequestMessageBuilder setAuthInfoSender(X500Principal sender) { if (sender != null) { setAuthInfoSender(new GeneralName(X500Name.getInstance(sender.getEncoded()))); } return this; }
@Override public HttpResponse handle(HttpRequest request, MiddlewareChain chain) { request = MixinUtils.mixin(request, new Class[]{PrincipalAvailable.class}); String clientDN = request.getHeaders().get("X-Client-DN"); if (!isAuthenticated((PrincipalAvailable) request) && clientDN != null) { RDN cn = new X500Name(clientDN).getRDNs(BCStyle.CN)[0]; String account = IETFUtils.valueToString(cn.getFirst().getValue()); } return castToHttpResponse(chain.next(request)); }
/** * Return possible empty collection with recipients matching the passed in RecipientId * * @param selector a recipient id to select against. * @return a collection of RecipientInformation objects. */ public Collection getRecipients( RecipientId selector) { if (selector instanceof KeyTransRecipientId) { KeyTransRecipientId keyTrans = (KeyTransRecipientId)selector; X500Name issuer = keyTrans.getIssuer(); byte[] subjectKeyId = keyTrans.getSubjectKeyIdentifier(); if (issuer != null && subjectKeyId != null) { List results = new ArrayList(); Collection match1 = getRecipients(new KeyTransRecipientId(issuer, keyTrans.getSerialNumber())); if (match1 != null) { results.addAll(match1); } Collection match2 = getRecipients(new KeyTransRecipientId(subjectKeyId)); if (match2 != null) { results.addAll(match2); } return results; } } List list = (ArrayList)table.get(selector); return list == null ? new ArrayList() : new ArrayList(list); }
public static String getSubjectCNFromCertificate(X509Certificate certificate) { try { X500Name x500name = new JcaX509CertificateHolder(certificate).getIssuer(); RDN cn = x500name.getRDNs(BCStyle.CN)[0]; return IETFUtils.valueToString(cn.getFirst().getValue()); } catch (CertificateEncodingException e) { log.error("Unable to get issuer CN", e); return null; } }
private X509CertificateObject generateCert(String keyName, KeyPair kp, boolean isCertAuthority, PublicKey signerPublicKey, PrivateKey signerPrivateKey) throws IOException, CertIOException, OperatorCreationException, CertificateException, NoSuchAlgorithmException { Calendar startDate = DateTimeUtils.calendar(); Calendar endDate = DateTimeUtils.calendar(); endDate.add(Calendar.YEAR, 100); BigInteger serialNumber = BigInteger.valueOf(startDate.getTimeInMillis()); X500Name issuer = new X500Name( IETFUtils.rDNsFromString("cn=localhost", RFC4519Style.INSTANCE)); JcaX509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(issuer, serialNumber, startDate.getTime(), endDate.getTime(), issuer, kp.getPublic()); JcaX509ExtensionUtils extensionUtils = new JcaX509ExtensionUtils(); certGen.addExtension(Extension.subjectKeyIdentifier, false, extensionUtils.createSubjectKeyIdentifier(kp.getPublic())); certGen.addExtension(Extension.basicConstraints, false, new BasicConstraints(isCertAuthority)); certGen.addExtension(Extension.authorityKeyIdentifier, false, extensionUtils.createAuthorityKeyIdentifier(signerPublicKey)); if (isCertAuthority) { certGen.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign)); } X509CertificateHolder cert = certGen.build( new JcaContentSignerBuilder(SIGNING_ALGORITHM).build(signerPrivateKey)); return new X509CertificateObject(cert.toASN1Structure()); }
public static ResponderID getInstance( Object obj) { if (obj instanceof ResponderID) { return (ResponderID)obj; } else if (obj instanceof DEROctetString) { return new ResponderID((DEROctetString)obj); } else if (obj instanceof ASN1TaggedObject) { ASN1TaggedObject o = (ASN1TaggedObject)obj; if (o.getTagNo() == 1) { return new ResponderID(X500Name.getInstance(o, true)); } else { return new ResponderID(ASN1OctetString.getInstance(o, true)); } } return new ResponderID(X500Name.getInstance(obj)); }
public static long fpCanonicalizedName(X500Name name) { ParamUtil.requireNonNull("name", name); String canonicalizedName = canonicalizName(name); byte[] encoded; try { encoded = canonicalizedName.getBytes("UTF-8"); } catch (UnsupportedEncodingException ex) { encoded = canonicalizedName.getBytes(); } return FpIdCalculator.hash(encoded); }
/** * Create a builder for a version 3 certificate. * * @param issuer the certificate issuer * @param serial the certificate serial number * @param notBefore the date before which the certificate is not valid * @param notAfter the date after which the certificate is not valid * @param subject the certificate subject * @param publicKeyInfo the info structure for the public key to be associated with this certificate. */ public X509v3CertificateBuilder(X500Name issuer, BigInteger serial, Date notBefore, Date notAfter, X500Name subject, SubjectPublicKeyInfo publicKeyInfo) { tbsGen = new V3TBSCertificateGenerator(); tbsGen.setSerialNumber(new ASN1Integer(serial)); tbsGen.setIssuer(issuer); tbsGen.setStartDate(new Time(notBefore)); tbsGen.setEndDate(new Time(notAfter)); tbsGen.setSubject(subject); tbsGen.setSubjectPublicKeyInfo(publicKeyInfo); extGenerator = new ExtensionsGenerator(); }
public RevocationDetailsBuilder setIssuer(X500Name issuer) { if (issuer != null) { templateBuilder.setIssuer(issuer); } return this; }
public RevocationDetailsBuilder setSubject(X500Name subject) { if (subject != null) { templateBuilder.setSubject(subject); } return this; }
/** * Set the requestor name to the passed in X500Principal * * @param requestorName a X500Principal representing the requestor name. */ public OCSPReqBuilder setRequestorName( X500Name requestorName) { this.requestorName = new GeneralName(GeneralName.directoryName, requestorName); return this; }
public IssuerAndSerialNumber( X500Name name, BigInteger serialNumber) { this.name = name; this.serialNumber = new ASN1Integer(serialNumber); }
public IssuerAndSerialNumber( X509Name name, BigInteger certSerialNumber) { this.name = X500Name.getInstance(name.toASN1Primitive()); this.certSerialNumber = new ASN1Integer(certSerialNumber); }
public IssuerAndSerialNumber( X500Name name, BigInteger certSerialNumber) { this.name = name; this.certSerialNumber = new ASN1Integer(certSerialNumber); }
private static Pair<PrivateKey, X509Certificate> generateKeyAndCertificate(String asymmetric, String sign, int validityYears, String dn) throws NoSuchAlgorithmException, OperatorCreationException, CertificateException { Preconditions.checkArgument(validityYears > 0, "validityYears <= 0"); KeyPair keyPair = KeyPairGenerator.getInstance(asymmetric).generateKeyPair(); Date notBefore = new Date(System.currentTimeMillis()); Date notAfter = new Date(System.currentTimeMillis() + validityYears * 31536000000l); X500Name issuer = new X500Name(new X500Principal(dn).getName()); SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()); X509v1CertificateBuilder builder = new X509v1CertificateBuilder(issuer, BigInteger.ONE, notBefore, notAfter, issuer, publicKeyInfo); ContentSigner signer = new JcaContentSignerBuilder(sign).setProvider(new BouncyCastleProvider()).build(keyPair.getPrivate()); X509CertificateHolder holder = builder.build(signer); JcaX509CertificateConverter converter = new JcaX509CertificateConverter().setProvider(new BouncyCastleProvider()); X509Certificate certificate = converter.getCertificate(holder); return Pair.of(keyPair.getPrivate(), certificate); }