List of usage examples for org.bouncycastle.asn1.x509 SubjectPublicKeyInfo SubjectPublicKeyInfo
public SubjectPublicKeyInfo(ASN1Sequence seq)
From source file:ch.bfh.unicert.certimport.CertificateIssuer.java
License:GNU General Public License
public Certificate createClientCertificate(IdentityData id, String keyStorePath, PublicKey pk, int validity, String applicationIdentifier, String[] roles, String uniBoardWsdlURL, String uniBoardServiceURL, String section) throws CertificateCreationException { X509Certificate caCert;/*w ww .j a v a2 s.c om*/ RSAPrivateCrtKey privKey; try { caCert = this.readIssuerCertificate(this.issuerId); privKey = this.readPrivateKey(this.issuerId, this.privKeyPass); } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException ex) { logger.log(Level.SEVERE, null, ex); throw new CertificateCreationException("230 Could not create client certificate. Key error"); } RSAPrivateCrtKeyParameters cipherParams = this.createIssuerCipherParams(privKey); X509Certificate clientCert; Hashtable extension = new Hashtable(); extension.put(new DERObjectIdentifier(ExtensionOID.APPLICATION_IDENTIFIER.getOID()), new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(applicationIdentifier))); String completeRole = ""; for (String role : roles) { completeRole += role + ", "; } completeRole = completeRole.substring(0, completeRole.length() - 2); extension.put(new DERObjectIdentifier(ExtensionOID.ROLE.getOID()), new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(completeRole))); extension.put(new DERObjectIdentifier(ExtensionOID.IDENTITY_PROVIDER.getOID()), new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(id.getIdentityProvider()))); Map<String, String> extensionMap = new HashMap(); if (id.getOtherValues() != null) { for (Entry<ExtensionOID, String> entry : id.getOtherValues().entrySet()) { extension.put(new DERObjectIdentifier(entry.getKey().getOID()), new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(entry.getValue()))); extensionMap.put(entry.getKey().getName(), entry.getValue()); } } try { String x509NameString = ""; x509NameString += "CN=" + id.getCommonName(); if (id.getSurname() != null && !id.getSurname().equals("")) { x509NameString += ", SURNAME=" + id.getSurname(); } if (id.getGivenName() != null && !id.getGivenName().equals("")) { x509NameString += ", GIVENNAME=" + id.getGivenName(); } if (id.getUniqueIdentifier() != null && !id.getUniqueIdentifier().equals("")) { x509NameString += ", UID=" + id.getUniqueIdentifier(); } if (id.getOrganisation() != null && !id.getOrganisation().equals("")) { x509NameString += ", O=" + id.getOrganisation(); } if (id.getOrganisationUnit() != null && !id.getOrganisationUnit().equals("")) { x509NameString += ", OU=" + id.getOrganisationUnit(); } if (id.getCountryName() != null && !id.getCountryName().equals("")) { x509NameString += ", C=" + id.getCountryName(); } if (id.getState() != null && !id.getState().equals("")) { x509NameString += ", ST=" + id.getState(); } if (id.getLocality() != null && !id.getLocality().equals("")) { x509NameString += ", L=" + id.getLocality(); } X509Name x509Name = new X509Name(x509NameString); V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator(); certGen.setSerialNumber(new DERInteger(BigInteger.valueOf(System.currentTimeMillis()))); certGen.setIssuer(PrincipalUtil.getSubjectX509Principal(caCert)); certGen.setSubject(x509Name); certGen.setExtensions(new X509Extensions(extension)); DERObjectIdentifier sigOID = new DERObjectIdentifier("1.2.840.113549.1.1.5"); AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(sigOID, new DERNull()); certGen.setSignature(sigAlgId); certGen.setSubjectPublicKeyInfo(new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pk.getEncoded())).readObject())); certGen.setStartDate(new Time(new Date(System.currentTimeMillis()))); certGen.setEndDate(new Time(getExpiryDate(validity).getTime())); TBSCertificateStructure tbsCert = certGen.generateTBSCertificate(); //Sign certificate SHA1Digest digester = new SHA1Digest(); AsymmetricBlockCipher rsa = new PKCS1Encoding(new RSAEngine()); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); DEROutputStream dOut = new DEROutputStream(bOut); dOut.writeObject(tbsCert); byte[] signature; byte[] certBlock = bOut.toByteArray(); // first create digest digester.update(certBlock, 0, certBlock.length); byte[] hash = new byte[digester.getDigestSize()]; digester.doFinal(hash, 0); // then sign it rsa.init(true, cipherParams); DigestInfo dInfo = new DigestInfo(new AlgorithmIdentifier(X509ObjectIdentifiers.id_SHA1, null), hash); byte[] digest = dInfo.getEncoded(ASN1Encodable.DER); signature = rsa.processBlock(digest, 0, digest.length); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(tbsCert); v.add(sigAlgId); v.add(new DERBitString(signature)); // Create CRT data structure clientCert = new X509CertificateObject(new X509CertificateStructure(new DERSequence(v))); clientCert.verify(caCert.getPublicKey()); } catch (IOException | InvalidCipherTextException | CertificateException | NoSuchAlgorithmException | InvalidKeyException | NoSuchProviderException | SignatureException e) { logger.log(Level.SEVERE, "Could not create client certificate: {0}", new Object[] { e.getMessage() }); throw new CertificateCreationException("230 Could not create client certificate"); } Certificate cert = new Certificate(clientCert, id.getCommonName(), id.getUniqueIdentifier(), id.getOrganisation(), id.getOrganisationUnit(), id.getCountryName(), id.getState(), id.getLocality(), id.getSurname(), id.getGivenName(), applicationIdentifier, roles, id.getIdentityProvider(), extensionMap); //post message on UniBoard if corresponding JNDI parameter is defined postOnUniBoard(cert, uniBoardWsdlURL, uniBoardServiceURL, section, (RSAPublicKey) caCert.getPublicKey(), privKey); return cert; }
From source file:ch.bfh.unicert.issuer.CertificateIssuerBean.java
License:GNU General Public License
/** * Actually creates the requestor certificate. * * @param id requestor identity data//from ww w . j av a 2s .c o m * @param caCert certificate of the certification authority * @param cipherParams issuer private key parameters used for signing * @param pk public key of the requestor to certify * @param expiry the expiry date * @param applicationIdentifier the application identifier for which te certificate is issued * @param role role for which the certificate is issued * @return the certificate object containing the X509 certificate * @throws CertificateCreationException if an error occurs */ private Certificate createClientCertificate(IdentityData id, X509Certificate caCert, CipherParameters cipherParams, PublicKey pk, Calendar expiry, String applicationIdentifier, String[] roles) throws CertificateCreationException { X509Certificate clientCert; Hashtable extension = new Hashtable(); extension.put(new DERObjectIdentifier(ExtensionOID.APPLICATION_IDENTIFIER.getOID()), new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(applicationIdentifier))); String completeRole = ""; for (String role : roles) { completeRole += role + ", "; } completeRole = completeRole.substring(0, completeRole.length() - 2); extension.put(new DERObjectIdentifier(ExtensionOID.ROLE.getOID()), new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(completeRole))); extension.put(new DERObjectIdentifier(ExtensionOID.IDENTITY_PROVIDER.getOID()), new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(id.getIdentityProvider()))); Map<String, String> extensionMap = new HashMap(); if (id.getOtherValues() != null) { for (Entry<ExtensionOID, String> entry : id.getOtherValues().entrySet()) { extension.put(new DERObjectIdentifier(entry.getKey().getOID()), new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(entry.getValue()))); extensionMap.put(entry.getKey().getName(), entry.getValue()); } } try { String x509NameString = ""; x509NameString += "CN=" + id.getCommonName(); if (id.getSurname() != null && !id.getSurname().equals("")) { x509NameString += ", SURNAME=" + id.getSurname(); } if (id.getGivenName() != null && !id.getGivenName().equals("")) { x509NameString += ", GIVENNAME=" + id.getGivenName(); } if (id.getUniqueIdentifier() != null && !id.getUniqueIdentifier().equals("")) { x509NameString += ", UID=" + id.getUniqueIdentifier(); } if (id.getOrganisation() != null && !id.getOrganisation().equals("")) { x509NameString += ", O=" + id.getOrganisation(); } if (id.getOrganisationUnit() != null && !id.getOrganisationUnit().equals("")) { x509NameString += ", OU=" + id.getOrganisationUnit(); } if (id.getCountryName() != null && !id.getCountryName().equals("")) { x509NameString += ", C=" + id.getCountryName(); } if (id.getState() != null && !id.getState().equals("")) { x509NameString += ", ST=" + id.getState(); } if (id.getLocality() != null && !id.getLocality().equals("")) { x509NameString += ", L=" + id.getLocality(); } X509Name x509Name = new X509Name(x509NameString); V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator(); certGen.setSerialNumber(new DERInteger(BigInteger.valueOf(System.currentTimeMillis()))); certGen.setIssuer(PrincipalUtil.getSubjectX509Principal(caCert)); certGen.setSubject(x509Name); certGen.setExtensions(new X509Extensions(extension)); DERObjectIdentifier sigOID = new DERObjectIdentifier("1.2.840.113549.1.1.5"); AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(sigOID, new DERNull()); certGen.setSignature(sigAlgId); certGen.setSubjectPublicKeyInfo(new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pk.getEncoded())).readObject())); certGen.setStartDate(new Time(new Date(System.currentTimeMillis()))); certGen.setEndDate(new Time(expiry.getTime())); TBSCertificateStructure tbsCert = certGen.generateTBSCertificate(); //Sign certificate SHA1Digest digester = new SHA1Digest(); AsymmetricBlockCipher rsa = new PKCS1Encoding(new RSAEngine()); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); DEROutputStream dOut = new DEROutputStream(bOut); dOut.writeObject(tbsCert); byte[] signature; byte[] certBlock = bOut.toByteArray(); // first create digest digester.update(certBlock, 0, certBlock.length); byte[] hash = new byte[digester.getDigestSize()]; digester.doFinal(hash, 0); // then sign it rsa.init(true, cipherParams); DigestInfo dInfo = new DigestInfo(new AlgorithmIdentifier(X509ObjectIdentifiers.id_SHA1, null), hash); byte[] digest = dInfo.getEncoded(ASN1Encodable.DER); signature = rsa.processBlock(digest, 0, digest.length); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(tbsCert); v.add(sigAlgId); v.add(new DERBitString(signature)); // Create CRT data structure clientCert = new X509CertificateObject(new X509CertificateStructure(new DERSequence(v))); clientCert.verify(caCert.getPublicKey()); } catch (IOException | CertificateException | NoSuchAlgorithmException | InvalidKeyException | NoSuchProviderException | InvalidCipherTextException | SignatureException e) { logger.log(Level.SEVERE, "Could not create client certificate: {0}", new Object[] { e.getMessage() }); throw new CertificateCreationException("230 Could not create client certificate"); } return new Certificate(clientCert, id.getCommonName(), id.getUniqueIdentifier(), id.getOrganisation(), id.getOrganisationUnit(), id.getCountryName(), id.getState(), id.getLocality(), id.getSurname(), id.getGivenName(), applicationIdentifier, roles, id.getIdentityProvider(), extensionMap); }
From source file:com.aqnote.shared.cryptology.cert.gen.CertGenerator.java
License:Open Source License
public X509Certificate signCert(PKCS10CertificationRequest pkcs10CSR, X500Name issuer, KeyPair pKeyPair) throws Exception { SubjectPublicKeyInfo pkInfo = pkcs10CSR.getSubjectPublicKeyInfo(); RSAKeyParameters rsa = (RSAKeyParameters) PublicKeyFactory.createKey(pkInfo); RSAPublicKeySpec rsaSpec = new RSAPublicKeySpec(rsa.getModulus(), rsa.getExponent()); KeyFactory kf = KeyFactory.getInstance(ALG_RSA); PublicKey publicKey = kf.generatePublic(rsaSpec); SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo(ASN1Sequence.getInstance(publicKey.getEncoded())); X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuer, BigInteger.valueOf(System.currentTimeMillis()), new Date(System.currentTimeMillis() - DateConstant.ONE_DAY), new Date(System.currentTimeMillis() + DateConstant.ONE_YEAR), pkcs10CSR.getSubject(), keyInfo); ContentSigner signer = new JcaContentSignerBuilder(ALG_SIG_SHA256_RSA).setProvider(JCE_PROVIDER) .build(pKeyPair.getPrivate()); X509Certificate signedCert = new JcaX509CertificateConverter().setProvider(JCE_PROVIDER) .getCertificate(certBuilder.build(signer)); signedCert.verify(pKeyPair.getPublic()); return signedCert; }
From source file:com.example.androidtest.SslUtil.java
License:Open Source License
/** * Creates an AuthorityKeyIdentifier from a public key, name, and serial * number.//from w w w. j av a 2 s .co 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.linkedin.mitm.services.AbstractX509CertificateService.java
License:Open Source License
/** * Create subjectKeyIdentifier//from w ww . j a va2 s .c o m * The Subject Key Identifier extension identifies the public key certified by this certificate. * This extension provides a way of distinguishing public keys if more than one is available for * a given subject name. * i.e. * Identifier: Subject Key Identifier - 2.5.29.14 * Critical: no * Key Identifier: * 3B:46:83:85:27:BC:F5:9D:8E:63:E3:BE:79:EF:AF:79: * 9C:37:85:84 * * */ protected SubjectKeyIdentifier createSubjectKeyIdentifier(PublicKey publicKey) throws IOException { try (ByteArrayInputStream bais = new ByteArrayInputStream(publicKey.getEncoded()); ASN1InputStream ais = new ASN1InputStream(bais)) { ASN1Sequence asn1Sequence = (ASN1Sequence) ais.readObject(); SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo(asn1Sequence); return new BcX509ExtensionUtils().createSubjectKeyIdentifier(subjectPublicKeyInfo); } }
From source file:com.mirth.connect.server.controllers.DefaultConfigurationController.java
License:Open Source License
/** * Checks for an existing certificate to use for secure communication between the server and * client. If no certficate exists, this will generate a new one. * /* w ww . ja va 2s .co m*/ */ private void generateDefaultCertificate(Provider provider, KeyStore keyStore, char[] keyPassword) throws Exception { final String certificateAlias = "mirthconnect"; if (!keyStore.containsAlias(certificateAlias)) { // Common CA and SSL cert attributes Date startDate = new Date(); // time from which certificate is valid Date expiryDate = DateUtils.addYears(startDate, 50); // time after which certificate is not valid KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", provider); keyPairGenerator.initialize(2048); KeyPair caKeyPair = keyPairGenerator.generateKeyPair(); logger.debug("generated new key pair for CA cert using provider: " + provider.getName()); // Generate CA cert X500Name caSubjectName = new X500Name("CN=Mirth Connect Certificate Authority"); SubjectPublicKeyInfo caSubjectKey = new SubjectPublicKeyInfo( ASN1Sequence.getInstance(caKeyPair.getPublic().getEncoded())); X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(caSubjectName, BigInteger.ONE, startDate, expiryDate, caSubjectName, caSubjectKey); certBuilder.addExtension(org.bouncycastle.asn1.x509.Extension.basicConstraints, true, new BasicConstraints(0)); ContentSigner sigGen = new JcaContentSignerBuilder("SHA256withRSA").setProvider(provider) .build(caKeyPair.getPrivate()); Certificate caCert = new JcaX509CertificateConverter().setProvider(provider) .getCertificate(certBuilder.build(sigGen)); // Generate SSL cert KeyPair sslKeyPair = keyPairGenerator.generateKeyPair(); logger.debug("generated new key pair for SSL cert using provider: " + provider.getName()); X500Name sslSubjectName = new X500Name("CN=mirth-connect"); SubjectPublicKeyInfo sslSubjectKey = new SubjectPublicKeyInfo( ASN1Sequence.getInstance(sslKeyPair.getPublic().getEncoded())); X509v3CertificateBuilder sslCertBuilder = new X509v3CertificateBuilder(caSubjectName, new BigInteger(50, new SecureRandom()), startDate, expiryDate, sslSubjectName, sslSubjectKey); sslCertBuilder.addExtension(org.bouncycastle.asn1.x509.Extension.authorityKeyIdentifier, false, new AuthorityKeyIdentifier(caCert.getEncoded())); sslCertBuilder.addExtension(org.bouncycastle.asn1.x509.Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifier(sslKeyPair.getPublic().getEncoded())); sigGen = new JcaContentSignerBuilder("SHA256withRSA").setProvider(provider) .build(caKeyPair.getPrivate()); Certificate sslCert = new JcaX509CertificateConverter().setProvider(provider) .getCertificate(sslCertBuilder.build(sigGen)); logger.debug("generated new certificate with serial number: " + ((X509Certificate) sslCert).getSerialNumber()); // add the generated SSL cert to the keystore using the key password keyStore.setKeyEntry(certificateAlias, sslKeyPair.getPrivate(), keyPassword, new Certificate[] { sslCert }); } else { logger.debug("found certificate in keystore"); } }
From source file:com.motorolamobility.studio.android.certmanager.core.KeyStoreUtils.java
License:Apache License
/** * Create a new X509 certificate for a given KeyPair * @param keyPair the {@link KeyPair} used to create the certificate, * RSAPublicKey and RSAPrivateKey are mandatory on keyPair, IllegalArgumentExeption will be thrown otherwise. * @param issuerName The issuer name to be used on the certificate * @param ownerName The owner name to be used on the certificate * @param expireDate The expire date//w w w . j a v a 2s .co m * @return The {@link X509Certificate} * @throws IOException * @throws OperatorCreationException * @throws CertificateException */ public static X509Certificate createX509Certificate(KeyPair keyPair, CertificateDetailsInfo certDetails) throws IOException, OperatorCreationException, CertificateException { PublicKey publicKey = keyPair.getPublic(); PrivateKey privateKey = keyPair.getPrivate(); if (!(publicKey instanceof RSAPublicKey) || !(privateKey instanceof RSAPrivateKey)) { throw new IllegalArgumentException(CertificateManagerNLS.KeyStoreUtils_RSA_Keys_Expected); } RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey; //Transform the PublicKey into the BouncyCastle expected format ASN1InputStream asn1InputStream = null; X509Certificate x509Certificate = null; try { asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(rsaPublicKey.getEncoded())); SubjectPublicKeyInfo pubKey = new SubjectPublicKeyInfo((ASN1Sequence) asn1InputStream.readObject()); X500NameBuilder nameBuilder = new X500NameBuilder(new BCStrictStyle()); addField(BCStyle.C, certDetails.getCountry(), nameBuilder); addField(BCStyle.ST, certDetails.getState(), nameBuilder); addField(BCStyle.L, certDetails.getLocality(), nameBuilder); addField(BCStyle.O, certDetails.getOrganization(), nameBuilder); addField(BCStyle.OU, certDetails.getOrganizationUnit(), nameBuilder); addField(BCStyle.CN, certDetails.getCommonName(), nameBuilder); X500Name subjectName = nameBuilder.build(); X500Name issuerName = subjectName; X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuerName, BigInteger.valueOf(new SecureRandom().nextInt()), GregorianCalendar.getInstance().getTime(), certDetails.getExpirationDate(), subjectName, pubKey); AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA"); //$NON-NLS-1$ AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); BcContentSignerBuilder sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId); //Create RSAKeyParameters, the private key format expected by Bouncy Castle RSAKeyParameters keyParams = new RSAKeyParameters(true, rsaPrivateKey.getPrivateExponent(), rsaPrivateKey.getModulus()); ContentSigner contentSigner = sigGen.build(keyParams); X509CertificateHolder certificateHolder = certBuilder.build(contentSigner); //Convert the X509Certificate from BouncyCastle format to the java.security format JcaX509CertificateConverter certConverter = new JcaX509CertificateConverter(); x509Certificate = certConverter.getCertificate(certificateHolder); } finally { if (asn1InputStream != null) { try { asn1InputStream.close(); } catch (IOException e) { StudioLogger.error("Could not close stream while creating X509 certificate. " + e.getMessage()); } } } return x509Certificate; }
From source file:com.msopentech.thali.utilities.universal.ThaliCryptoUtilities.java
License:Open Source License
/** * Creates a PKCS12 keystore and puts into it the submitted public/private key pair under the submitted * Key Alias using the submitted passphrase to 'secure' the file. * * Right now we only generate large RSA keys because I'm paranoid that the curves used in * Elliptic Curve crypto may have been designed by folks for whom security was not the paramount * concern. Once this issue is put to rest I would expect to switch to Elliptic Curve because * it is considered (with appropriate curves) to be more secure and is certainly faster. * @param keyPair/* ww w . j a v a 2 s . co m*/ * @param keyAlias * @param passphrase * @return */ public static KeyStore CreatePKCS12KeyStoreWithPublicPrivateKeyPair(KeyPair keyPair, String keyAlias, char[] passphrase) { try { byte[] publicKeyAsByteArray = keyPair.getPublic().getEncoded(); // Generate a cert for the public key Date startDate = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000); Date endDate = new Date( System.currentTimeMillis() + (ExpirationPeriodForCertsInDays * 24L * 60L * 60L * 1000L)); // Thali security is based on keys NOT on cert values. That is we are not trying to bind a name (like a DNS // address) to a key. The key IS the identity. But the X509 standard requires names so we stick something // in. X500Name x500Name = new X500Name(X500Name); SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo( ASN1Sequence.getInstance(publicKeyAsByteArray)); // Note that by not specify .setProvider("BC") we are using the default provider, this is because bouncy castle as // previously mentioned is installed on Android but is a challenge for the applet so I'll just use the default for now. ContentSigner contentSigner = new JcaContentSignerBuilder(SignerAlgorithm).build(keyPair.getPrivate()); X509v1CertificateBuilder x509v1CertificateBuilder = new X509v1CertificateBuilder(x500Name, BigInteger.ONE, startDate, endDate, x500Name, subjectPublicKeyInfo); X509CertificateHolder x509CertificateHolder = x509v1CertificateBuilder.build(contentSigner); JcaX509CertificateConverter jcaX509CertificateConverter = new JcaX509CertificateConverter(); X509Certificate x509Certificate = jcaX509CertificateConverter.getCertificate(x509CertificateHolder); // Store the private key and the cert in the keystore KeyStore.PrivateKeyEntry privateKeyEntry = new KeyStore.PrivateKeyEntry(keyPair.getPrivate(), new Certificate[] { x509Certificate }); KeyStore keyStore = KeyStore.getInstance(PrivateKeyHolderFormat); // Keystore has to be initialized before being used keyStore.load(null, null); keyStore.setEntry(keyAlias, privateKeyEntry, new KeyStore.PasswordProtection(passphrase)); return keyStore; } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } }
From source file:com.peterphi.std.crypto.keygen.CaHelper.java
License:Open Source License
/** * @param gen//from w w w . ja v a 2 s . c om * @param pubKey * * @throws IOException */ private static void addAuthorityKeyIdentifier(X509V3CertificateGenerator gen, PublicKey pubKey) throws Exception { { ASN1InputStream is = new ASN1InputStream(new ByteArrayInputStream(pubKey.getEncoded())); try { SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo((ASN1Sequence) is.readObject()); AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki); gen.addExtension(X509Extensions.AuthorityKeyIdentifier.getId(), false, aki); } finally { IOUtils.closeQuietly(is); } } }
From source file:com.peterphi.std.crypto.keygen.CaHelper.java
License:Open Source License
/** * @param gen//from w ww.j a v a 2 s. c o m * @param pubKey * * @throws IOException */ private static void addSubjectKeyIdentifier(X509V3CertificateGenerator gen, PublicKey pubKey) throws Exception { { ASN1InputStream is = new ASN1InputStream(new ByteArrayInputStream(pubKey.getEncoded())); try { SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo((ASN1Sequence) is.readObject()); SubjectKeyIdentifier ski = new SubjectKeyIdentifier(spki); gen.addExtension(X509Extensions.SubjectKeyIdentifier.getId(), false, ski); } finally { IOUtils.closeQuietly(is); } } }