List of usage examples for org.bouncycastle.asn1.x509 AuthorityKeyIdentifier AuthorityKeyIdentifier
public AuthorityKeyIdentifier(byte[] keyIdentifier, GeneralNames name, BigInteger serialNumber)
From source file:com.example.androidtest.SslUtil.java
License:Open Source License
/** * Creates an AuthorityKeyIdentifier from a public key, name, and serial * number./*from ww w.j a v a 2 s .c o m*/ * <p> * {@link AuthorityKeyIdentifierStructure} is <i>almost</i> perfect for this, * but sadly it does not have a constructor suitable for us: * {@link AuthorityKeyIdentifierStructure#AuthorityKeyIdentifierStructure(PublicKey)} * does not set the serial number or name (which is important to us), while * {@link AuthorityKeyIdentifierStructure#AuthorityKeyIdentifierStructure(X509Certificate)} * sets those fields but needs a completed certificate to do so. * <p> * This method addresses the gap in available {@link AuthorityKeyIdentifier} * constructors provided by BouncyCastle; its implementation is derived from * {@link AuthorityKeyIdentifierStructure#AuthorityKeyIdentifierStructure(X509Certificate)}. * * @param publicKey the public key * @param name the name * @param serialNumber the serial number * @return a new {@link AuthorityKeyIdentifier} */ private static AuthorityKeyIdentifier createAuthorityKeyIdentifier(PublicKey publicKey, X509Name name, BigInteger serialNumber) { GeneralName genName = new GeneralName(name); SubjectPublicKeyInfo info; try { info = new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(publicKey.getEncoded()).readObject()); } catch (IOException e) { throw new RuntimeException("Error encoding public key"); } return new AuthorityKeyIdentifier(info, new GeneralNames(genName), serialNumber); }
From source file:com.otterca.common.crypto.X509CertificateBuilderImpl.java
License:Apache License
/** * Set Authority Key Identifier (RFC3280 4.2.1.1) * // ww w . java 2 s.c o m * @throws InvalidKeyException * @throws CertificateParsingException */ protected final void setAKID() throws InvalidKeyException, CertificateParsingException { if (issuer != null) { // signed certificates AuthorityKeyIdentifierStructure akis = new AuthorityKeyIdentifierStructure(issuer); generator.addExtension(X509Extensions.AuthorityKeyIdentifier, false, akis); } else { // self-signed certificates since we already require subjectDN = // issuerDN GeneralNames issuerName = new GeneralNames(new GeneralName(GeneralName.directoryName, issuerDN)); AuthorityKeyIdentifier akis = new AuthorityKeyIdentifierStructure(pubkey); akis = new AuthorityKeyIdentifier(akis.getKeyIdentifier(), issuerName, serialNumber); generator.addExtension(X509Extensions.AuthorityKeyIdentifier, false, akis); } }
From source file:eu.optimis.ics.BrokerVPNCredentials.CACredentials.java
License:Open Source License
public X509CertificateHolder genCACertificate(KeyPair CAKP) throws CertIOException, NoSuchAlgorithmException { BigInteger serial = BigInteger.valueOf(42); Date notBefore = new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30); Date notAfter = new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365)); SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(CAKP.getPublic().getEncoded()); // Same issuer and subject for the self-signed CA certificate X500Name issuer = new X500Name( "C=UK, ST=Suffolk, L=Ipswich, O=BT, OU=R&T, CN=CloudShadow, Name=Ali, emailAddress=ali.sajjad@bt.com"); X500Name subject = new X500Name( "C=UK, ST=Suffolk, L=Ipswich, O=BT, OU=R&T, CN=CloudShadow, Name=Ali, emailAddress=ali.sajjad@bt.com"); X509v3CertificateBuilder v3CertBuilder = new X509v3CertificateBuilder(issuer, serial, notBefore, notAfter, subject, publicKeyInfo);/*from w ww.j a va2 s . c o m*/ GeneralNames gNames = new GeneralNames(new GeneralName(issuer)); v3CertBuilder.addExtension(X509Extension.subjectKeyIdentifier, false, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(publicKeyInfo)); v3CertBuilder.addExtension(X509Extension.authorityKeyIdentifier, false, new AuthorityKeyIdentifier(publicKeyInfo, gNames, serial)); v3CertBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(true)); ContentSigner sigGen = null; try { sigGen = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(CAKP.getPrivate()); } catch (OperatorCreationException e) { e.printStackTrace(); } return v3CertBuilder.build(sigGen); }
From source file:eu.optimis.ics.Credentials.CACredentials.java
License:Open Source License
protected X509CertificateHolder genCACertificate(KeyPair CAKP) { BigInteger serial = BigInteger.valueOf(new SecureRandom().nextLong()).abs(); Date notBefore = new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30); Date notAfter = new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365)); SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(CAKP.getPublic().getEncoded()); // Same issuer and subject for the self-signed CA certificate X500Name issuer = new X500Name( "C=UK, ST=Suffolk, L=Ipswich, O=BT, OU=R&T, CN=CloudShadow, Name=Ali, emailAddress=ali.sajjad@bt.com"); X500Name subject = new X500Name( "C=UK, ST=Suffolk, L=Ipswich, O=BT, OU=R&T, CN=CloudShadow, Name=Ali, emailAddress=ali.sajjad@bt.com"); X509v3CertificateBuilder v3CertBuilder = new X509v3CertificateBuilder(issuer, serial, notBefore, notAfter, subject, publicKeyInfo);/*from w w w . j av a2 s .c o m*/ GeneralNames gNames = new GeneralNames(new GeneralName(issuer)); v3CertBuilder.addExtension(X509Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifier(publicKeyInfo)); v3CertBuilder.addExtension(X509Extension.authorityKeyIdentifier, false, new AuthorityKeyIdentifier(publicKeyInfo, gNames, serial)); v3CertBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(true)); ContentSigner sigGen = null; try { sigGen = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(CAKP.getPrivate()); } catch (OperatorCreationException e) { e.printStackTrace(); } return v3CertBuilder.build(sigGen); }
From source file:mitm.common.security.certificate.impl.StandardX509CertificateBuilder.java
License:Open Source License
protected AuthorityKeyIdentifier getAuthorityKeyIdentifier(X509Certificate issuerCertificate) throws CertificateParsingException, IOException { X509CertificateInspector inspector = new X509CertificateInspector(issuerCertificate); /*//from w w w .j av a 2 s . c o m * We must add the issuer of the issuer certificate! not the subject of the issuer certificate * The subject / serial number is already contained in the certificate to be issued. The * issuer of the issuer is added to identify multiple paths if an intermediate can be signed * by multiple ca's */ GeneralNames names = new GeneralNames(new GeneralName(inspector.getIssuerX500Name())); AuthorityKeyIdentifier authorityKeyIdentifier; byte[] subjectKeyIdentifier = inspector.getSubjectKeyIdentifier(); if (subjectKeyIdentifier != null) { authorityKeyIdentifier = new AuthorityKeyIdentifier(subjectKeyIdentifier, names, issuerCertificate.getSerialNumber()); } else { authorityKeyIdentifier = new AuthorityKeyIdentifier(names, issuerCertificate.getSerialNumber()); } return authorityKeyIdentifier; }
From source file:net.solarnetwork.node.setup.test.PKITestUtils.java
License:Open Source License
public static X509Certificate generateNewCACert(PublicKey publicKey, String subject, X509Certificate issuer, PrivateKey issuerKey, String caDN) throws Exception { final X500Name issuerDn = (issuer == null ? new X500Name(subject) : JcaX500NameUtil.getSubject(issuer)); final X500Name subjectDn = new X500Name(subject); final BigInteger serial = getNextSerialNumber(); final Date notBefore = new Date(); final Date notAfter = new Date(System.currentTimeMillis() + 1000L * 60L * 60L); JcaX509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuerDn, serial, notBefore, notAfter, subjectDn, publicKey);//w ww .j av a 2s. c om // add "CA" extension BasicConstraints basicConstraints; if (issuer == null) { basicConstraints = new BasicConstraints(true); } else { int issuerPathLength = issuer.getBasicConstraints(); basicConstraints = new BasicConstraints(issuerPathLength - 1); } builder.addExtension(X509Extension.basicConstraints, true, basicConstraints); // add subjectKeyIdentifier JcaX509ExtensionUtils utils = new JcaX509ExtensionUtils(); SubjectKeyIdentifier ski = utils.createSubjectKeyIdentifier(publicKey); builder.addExtension(X509Extension.subjectKeyIdentifier, false, ski); // add authorityKeyIdentifier GeneralNames issuerName = new GeneralNames(new GeneralName(GeneralName.directoryName, caDN)); AuthorityKeyIdentifier aki = utils.createAuthorityKeyIdentifier(publicKey); aki = new AuthorityKeyIdentifier(aki.getKeyIdentifier(), issuerName, serial); builder.addExtension(X509Extension.authorityKeyIdentifier, false, aki); // add keyUsage X509KeyUsage keyUsage = new X509KeyUsage(X509KeyUsage.cRLSign | X509KeyUsage.digitalSignature | X509KeyUsage.keyCertSign | X509KeyUsage.nonRepudiation); builder.addExtension(X509Extension.keyUsage, true, keyUsage); JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder("SHA256WithRSA"); ContentSigner signer = signerBuilder.build(issuerKey); X509CertificateHolder holder = builder.build(signer); JcaX509CertificateConverter converter = new JcaX509CertificateConverter(); return converter.getCertificate(holder); }
From source file:org.kopi.ebics.certificate.X509Generator.java
License:Open Source License
/** * Returns the <code>AuthorityKeyIdentifier</code> corresponding * to a given <code>PublicKey</code> * @param publicKey the given public key * @param issuer the certificate issuer/* w w w .java 2s. co m*/ * @param serial the certificate serial number * @return the authority key identifier of the public key * @throws IOException */ private AuthorityKeyIdentifier getAuthorityKeyIdentifier(PublicKey publicKey, String issuer, BigInteger serial) throws IOException { InputStream input; SubjectPublicKeyInfo keyInfo; ASN1EncodableVector vector; input = new ByteArrayInputStream(publicKey.getEncoded()); keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) new ASN1InputStream(input).readObject()); vector = new ASN1EncodableVector(); vector.add(new GeneralName(new X509Name(issuer))); return new AuthorityKeyIdentifier(keyInfo, new GeneralNames(new DERSequence(vector)), serial); }
From source file:org.mailster.core.crypto.CertificateUtilities.java
License:Open Source License
/** * Generate a sample V3 certificate to use as an intermediate or end entity * certificate depending on the <code>isEndEntity</code> argument. *//*from w w w.j av a2 s .c o m*/ private static X509Certificate generateV3Certificate(String DN, boolean isEndEntity, PublicKey entityKey, PrivateKey caKey, X509Certificate caCert) throws Exception { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setIssuerDN(caCert.getSubjectX500Principal()); certGen.setSubjectDN(new X509Name(true, X509Name.DefaultLookUp, DN)); setSerialNumberAndValidityPeriod(certGen, false, DEFAULT_VALIDITY_PERIOD); certGen.setPublicKey(entityKey); certGen.setSignatureAlgorithm("SHA1WithRSAEncryption"); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifier(caCert.getEncoded(), new GeneralNames(new GeneralName( new X509Name(true, X509Name.DefaultLookUp, caCert.getSubjectDN().getName()))), caCert.getSerialNumber())); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(entityKey)); if (isEndEntity) { certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); } else { certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(0)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign)); } return certGen.generate(caKey, "BC"); }
From source file:org.nimbustools.auto_common.ezpz_ca.CAFactory.java
License:Apache License
public X509Certificate create(String baseName, int months, KeyPair keyPair) throws Exception { final X509Principal newprincipal = new X509Principal("O=Auto,OU=" + baseName + ",CN=CA"); this.certGen.reset(); /*/* w ww . j a v a 2 s . com*/ "The entity that created the certificate is responsible for assigning it a serial number to distinguish it from other certificates it issues. This information is used in numerous ways, for example when a certificate is revoked its serial number is placed in a Certificate Revocation List (CRL)" */ this.certGen.setSerialNumber(BigInteger.ZERO); final Calendar expires = Calendar.getInstance(); expires.add(Calendar.MONTH, months); this.certGen.setNotBefore(new Date(System.currentTimeMillis() - 10000)); this.certGen.setNotAfter(expires.getTime()); this.certGen.setSubjectDN(newprincipal); this.certGen.setIssuerDN(newprincipal); this.certGen.setSignatureAlgorithm("SHA1withRSA"); final PublicKey pubkey = keyPair.getPublic(); this.certGen.setPublicKey(pubkey); // begin X509/BC security nastiness, not sure these are the very best // choices but it is working... final ByteArrayInputStream in = new ByteArrayInputStream(pubkey.getEncoded()); final SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo( (ASN1Sequence) new DERInputStream(in).readObject()); final SubjectKeyIdentifier ski = new SubjectKeyIdentifier(spki); final ByteArrayInputStream in2 = new ByteArrayInputStream(newprincipal.getEncoded()); final GeneralNames generalNames = new GeneralNames((ASN1Sequence) new DERInputStream(in2).readObject()); final AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(spki, generalNames, BigInteger.ZERO); this.certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true)); /* this.certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); */ this.certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, ski); this.certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, aki); this.certGen.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.cRLSign | KeyUsage.keyCertSign)); return this.certGen.generateX509Certificate(keyPair.getPrivate()); }
From source file:org.opcfoundation.ua.utils.CertificateUtils.java
License:Open Source License
/** * /* w ww.j a va 2 s .c om*/ * @param commonName - Common Name (CN) for generated certificate * @param organisation - Organisation (O) for generated certificate * @param applicationUri - Alternative name (one of x509 extensiontype) for generated certificate. Must not be null * @param validityTime - the time that the certificate is valid (in days) * @return * @throws IOException * @throws InvalidKeySpecException * @throws NoSuchAlgorithmException * @throws CertificateEncodingException * @throws InvalidKeyException * @throws IllegalStateException * @throws NoSuchProviderException * @throws SignatureException * @throws CertificateParsingException */ public static org.opcfoundation.ua.transport.security.KeyPair createApplicationInstanceCertificate( String commonName, String organisation, String applicationUri, int validityTime) throws IOException, InvalidKeySpecException, NoSuchAlgorithmException, CertificateEncodingException, InvalidKeyException, IllegalStateException, NoSuchProviderException, SignatureException, CertificateParsingException { if (applicationUri == null) throw new NullPointerException("applicationUri must not be null"); //Add provider for generator Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); //Initializes generator SecureRandom srForCert = new SecureRandom(); RSAKeyPairGenerator genForCert = new RSAKeyPairGenerator(); //Used for generating prime Random r = new Random(System.currentTimeMillis()); int random = -1; while (random < 3) { random = r.nextInt(32); } //calculate(generate) possible value for public modulus //used method is "monte carlo -algorithm", so we calculate it as long as it generates value. BigInteger value = null; while (value == null) { value = BigInteger.probablePrime(random, new SecureRandom()); } //Generate (Java) keypair genForCert.init(new RSAKeyGenerationParameters(value, srForCert, KEY_SIZE, 80)); AsymmetricCipherKeyPair keypairForCert = genForCert.generateKeyPair(); //Extract the keys from parameters logger.debug("Generated keypair, extracting components and creating public structure for certificate"); RSAKeyParameters clientPublicKey = (RSAKeyParameters) keypairForCert.getPublic(); RSAPrivateCrtKeyParameters clientPrivateKey = (RSAPrivateCrtKeyParameters) keypairForCert.getPrivate(); // used to get proper encoding for the certificate RSAPublicKeyStructure clientPkStruct = new RSAPublicKeyStructure(clientPublicKey.getModulus(), clientPublicKey.getExponent()); logger.debug("New public key is '" + makeHexString(clientPkStruct.getEncoded()) + ", exponent=" + clientPublicKey.getExponent() + ", modulus=" + clientPublicKey.getModulus()); // JCE format needed for the certificate - because getEncoded() is necessary... PublicKey certPubKey = KeyFactory.getInstance("RSA") .generatePublic(new RSAPublicKeySpec(clientPublicKey.getModulus(), clientPublicKey.getExponent())); // and this one for the KeyStore PrivateKey certPrivKey = KeyFactory.getInstance("RSA").generatePrivate( new RSAPrivateCrtKeySpec(clientPublicKey.getModulus(), clientPublicKey.getExponent(), clientPrivateKey.getExponent(), clientPrivateKey.getP(), clientPrivateKey.getQ(), clientPrivateKey.getDP(), clientPrivateKey.getDQ(), clientPrivateKey.getQInv())); //The data for the certificate.. Calendar expiryTime = Calendar.getInstance(); expiryTime.add(Calendar.DAY_OF_YEAR, validityTime); X509Name certificateX509Name = new X509Name( "CN=" + commonName + ", O=" + organisation + ", C=" + System.getProperty("user.country")); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); BigInteger serial = BigInteger.valueOf(System.currentTimeMillis()); certGen.setSerialNumber(serial); //Issuer and subject must be the same (because this is self signed) certGen.setIssuerDN(certificateX509Name); certGen.setSubjectDN(certificateX509Name); //expiry & start time for this certificate certGen.setNotBefore(new Date(System.currentTimeMillis() - 1000 * 60 * 60)); //take 60 minutes (1000 ms * 60 s * 60) away from system clock (in case there is some lag in system clocks) certGen.setNotAfter(expiryTime.getTime()); certGen.setPublicKey(certPubKey); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); //******* X.509 V3 Extensions ***************** SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(certPubKey.getEncoded())).readObject()); SubjectKeyIdentifier ski = new SubjectKeyIdentifier(apki); /*certGen.addExtension(X509Extensions.SubjectKeyIdentifier, true, new DEROctetString(ski//new SubjectKeyIdentifier Structure(apki/*certPubKey))); */ certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, ski); certGen.addExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, /*new DEROctetString(new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.nonRepudiation | KeyUsage.dataEncipherment | KeyUsage.keyCertSign ))*/new KeyUsage( KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.nonRepudiation | KeyUsage.dataEncipherment | KeyUsage.keyCertSign)); BasicConstraints b = new BasicConstraints(false); Vector<KeyPurposeId> extendedKeyUsages = new Vector<KeyPurposeId>(); extendedKeyUsages.add(KeyPurposeId.id_kp_serverAuth); extendedKeyUsages.add(KeyPurposeId.id_kp_clientAuth); certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, /*new DEROctetString(new ExtendedKeyUsage(extendedKeyUsages))*/new ExtendedKeyUsage( extendedKeyUsages)); // create the extension value ASN1EncodableVector names = new ASN1EncodableVector(); names.add(new GeneralName(GeneralName.uniformResourceIdentifier, applicationUri)); // GeneralName dnsName = new GeneralName(GeneralName.dNSName, applicationUri); // names.add(dnsName); final GeneralNames subjectAltNames = new GeneralNames(new DERSequence(names)); certGen.addExtension(X509Extensions.SubjectAlternativeName, true, subjectAltNames); // AuthorityKeyIdentifier final GeneralNames certificateIssuer = new GeneralNames(new GeneralName(certificateX509Name)); AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki, certificateIssuer, serial); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, aki); //***** generate certificate ***********/ X509Certificate cert = certGen.generate(certPrivKey, "BC"); //Encapsulate Certificate and private key to CertificateKeyPair Cert certificate = new Cert(cert); org.opcfoundation.ua.transport.security.PrivKey UAkey = new org.opcfoundation.ua.transport.security.PrivKey( (RSAPrivateKey) certPrivKey); return new org.opcfoundation.ua.transport.security.KeyPair(certificate, UAkey); }