Search in sources :

Example 36 with org.bouncycastle.asn1.x509

use of org.bouncycastle.asn1.x509 in project athenz by yahoo.

the class ZTSClient method getAWSLambdaServiceCertificate.

/**
 * For AWS Lambda functions generate a new private key, request a
 * x.509 certificate based on the requested CSR and return both to
 * the client in order to establish tls connections with other
 * Athenz enabled services.
 * @param domainName name of the domain
 * @param serviceName name of the service
 * @param account AWS account name that the function runs in
 * @param provider name of the provider service for AWS Lambda
 * @return AWSLambdaIdentity with private key and certificate
 */
public AWSLambdaIdentity getAWSLambdaServiceCertificate(String domainName, String serviceName, String account, String provider) {
    if (domainName == null || serviceName == null) {
        throw new IllegalArgumentException("Domain and Service must be specified");
    }
    if (account == null || provider == null) {
        throw new IllegalArgumentException("AWS Account and Provider must be specified");
    }
    if (x509CsrDomain == null) {
        throw new IllegalArgumentException("X509 CSR Domain must be specified");
    }
    // first we're going to generate a private key for the request
    AWSLambdaIdentity lambdaIdentity = new AWSLambdaIdentity();
    try {
        lambdaIdentity.setPrivateKey(Crypto.generateRSAPrivateKey(2048));
    } catch (CryptoException ex) {
        throw new ZTSClientException(ResourceException.BAD_REQUEST, ex.getMessage());
    }
    // we need to generate an csr with an instance register object
    InstanceRegisterInformation info = new InstanceRegisterInformation();
    info.setDomain(domainName.toLowerCase());
    info.setService(serviceName.toLowerCase());
    info.setProvider(provider.toLowerCase());
    final String athenzService = info.getDomain() + "." + info.getService();
    // generate our dn which will be based on our service name
    StringBuilder dnBuilder = new StringBuilder(128);
    dnBuilder.append("cn=");
    dnBuilder.append(athenzService);
    if (x509CsrDn != null) {
        dnBuilder.append(',');
        dnBuilder.append(x509CsrDn);
    }
    // now let's generate our dsnName field based on our principal's details
    GeneralName[] sanArray = new GeneralName[3];
    final String hostBuilder = info.getService() + '.' + info.getDomain().replace('.', '-') + '.' + x509CsrDomain;
    sanArray[0] = new GeneralName(GeneralName.dNSName, new DERIA5String(hostBuilder));
    final String instanceHostBuilder = "lambda-" + account + '-' + info.getService() + ".instanceid.athenz." + x509CsrDomain;
    sanArray[1] = new GeneralName(GeneralName.dNSName, new DERIA5String(instanceHostBuilder));
    final String spiffeUri = SPIFFE_URI + info.getDomain() + SPIFFE_COMP_SERVICE + info.getService();
    sanArray[2] = new GeneralName(GeneralName.uniformResourceIdentifier, new DERIA5String(spiffeUri));
    try {
        info.setCsr(Crypto.generateX509CSR(lambdaIdentity.getPrivateKey(), dnBuilder.toString(), sanArray));
    } catch (OperatorCreationException | IOException ex) {
        throw new ZTSClientException(ResourceException.BAD_REQUEST, ex.getMessage());
    }
    // finally obtain attestation data for lambda
    info.setAttestationData(getAWSLambdaAttestationData(athenzService, account));
    // request the x.509 certificate from zts server
    Map<String, List<String>> responseHeaders = new HashMap<>();
    InstanceIdentity identity = postInstanceRegisterInformation(info, responseHeaders);
    try {
        lambdaIdentity.setX509Certificate(Crypto.loadX509Certificate(identity.getX509Certificate()));
    } catch (CryptoException ex) {
        throw new ZTSClientException(ResourceException.BAD_REQUEST, ex.getMessage());
    }
    lambdaIdentity.setCaCertificates(identity.getX509CertificateSigner());
    return lambdaIdentity;
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) DERIA5String(org.bouncycastle.asn1.DERIA5String) IOException(java.io.IOException) DERIA5String(org.bouncycastle.asn1.DERIA5String) GeneralName(org.bouncycastle.asn1.x509.GeneralName) CryptoException(com.yahoo.athenz.auth.util.CryptoException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException)

Example 37 with org.bouncycastle.asn1.x509

use of org.bouncycastle.asn1.x509 in project athenz by yahoo.

the class SelfCertSignerFactory method create.

@Override
public CertSigner create() {
    // extract the private key for this self cert signer
    final String pKeyFileName = System.getProperty(ZTSConsts.ZTS_PROP_SELF_SIGNER_PRIVATE_KEY_FNAME);
    final String pKeyPassword = System.getProperty(ZTSConsts.ZTS_PROP_SELF_SIGNER_PRIVATE_KEY_PASSWORD);
    final String csrDn = System.getProperty(ZTSConsts.ZTS_PROP_SELF_SIGNER_CERT_DN, "cn=Self Signed Athenz CA,o=Athenz,c=US");
    final int maxCertExpiryTimeMins = Integer.parseInt(System.getProperty(ZTSConsts.ZTS_PROP_CERTSIGN_MAX_EXPIRY_TIME, "43200"));
    if (StringUtil.isEmpty(pKeyFileName)) {
        LOGGER.error("No private key path available for Self Cert Signer Factory");
        return null;
    }
    File caKey = new File(pKeyFileName);
    PrivateKey caPrivateKey = Crypto.loadPrivateKey(caKey, pKeyPassword);
    // now generate a CSR for our own CA and self sign it
    String csr;
    try {
        csr = Crypto.generateX509CSR(caPrivateKey, csrDn, null);
    } catch (IllegalArgumentException | OperatorCreationException | IOException ex) {
        LOGGER.error("Unable to generate X509 CSR for dn: {}, error: {}", csrDn, ex.getMessage());
        return null;
    }
    // generate our self-signed certificate
    X500Principal subject = new X500Principal(csrDn);
    X500Name issuer = X500Name.getInstance(subject.getEncoded());
    PKCS10CertificationRequest certReq = Crypto.getPKCS10CertRequest(csr);
    X509Certificate caCertificate = Crypto.generateX509Certificate(certReq, caPrivateKey, issuer, 30 * 24 * 60, true);
    return new KeyStoreCertSigner(caCertificate, caPrivateKey, maxCertExpiryTimeMins);
}
Also used : PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) PrivateKey(java.security.PrivateKey) IOException(java.io.IOException) X500Name(org.bouncycastle.asn1.x500.X500Name) X509Certificate(java.security.cert.X509Certificate) X500Principal(javax.security.auth.x500.X500Principal) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) File(java.io.File)

Example 38 with org.bouncycastle.asn1.x509

use of org.bouncycastle.asn1.x509 in project groovity by disney.

the class TestKeys method testCertificate.

@Test
public void testCertificate() throws Exception {
    URI keyLoc = new URI("mem:myCertificate");
    KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
    generator.initialize(2048);
    KeyPair keyPair = generator.generateKeyPair();
    X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(new X500Name("CN=Some authority, OU=DATG, O=Disney, C=US"), new BigInteger(64, new SecureRandom()), // yesterday
    new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000), // 10 years
    new Date(System.currentTimeMillis() + 10 * 365 * 24 * 60 * 60 * 1000), new X500Name("DN=mySubject"), SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()));
    JcaContentSignerBuilder builder = new JcaContentSignerBuilder("SHA256withRSA");
    ContentSigner signer = builder.build(keyPair.getPrivate());
    byte[] certBytes = certBuilder.build(signer).getEncoded();
    Certificate cert = CertificateFactory.getInstance("X.509").generateCertificate(new ByteArrayInputStream(certBytes));
    URIParcel<Certificate> certParcel = new URIParcel<Certificate>(Certificate.class, keyLoc);
    certParcel.put(cert);
    byte[] rawBytes = URIParcel.get(keyLoc, byte[].class);
    Assert.assertTrue("Expected X509 certificate", new String(rawBytes).startsWith("-----BEGIN CERTIFICATE-----"));
    Certificate rc = URIParcel.get(keyLoc, Certificate.class);
    Assert.assertEquals(keyPair.getPublic(), rc.getPublicKey());
}
Also used : KeyPair(java.security.KeyPair) URIParcel(com.disney.uriparcel.URIParcel) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) SecureRandom(java.security.SecureRandom) KeyPairGenerator(java.security.KeyPairGenerator) X500Name(org.bouncycastle.asn1.x500.X500Name) URI(java.net.URI) Date(java.util.Date) ByteArrayInputStream(java.io.ByteArrayInputStream) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) BigInteger(java.math.BigInteger) Certificate(java.security.cert.Certificate) Test(org.junit.Test)

Example 39 with org.bouncycastle.asn1.x509

use of org.bouncycastle.asn1.x509 in project keystore-explorer by kaikramer.

the class OpenSslPvkUtil method load.

/**
 * Load an unencrypted OpenSSL private key from the stream. The encoding of
 * the private key may be PEM or DER.
 *
 * @param is
 *            Stream to load the unencrypted private key from
 * @return The private key
 * @throws PrivateKeyEncryptedException
 *             If private key is encrypted
 * @throws CryptoException
 *             Problem encountered while loading the private key
 * @throws IOException
 *             An I/O error occurred
 */
public static PrivateKey load(InputStream is) throws CryptoException, IOException {
    byte[] streamContents = ReadUtil.readFully(is);
    EncryptionType encType = getEncryptionType(new ByteArrayInputStream(streamContents));
    if (encType == null) {
        throw new CryptoException(res.getString("NotValidOpenSsl.exception.message"));
    }
    if (encType == ENCRYPTED) {
        throw new PrivateKeyEncryptedException(res.getString("OpenSslIsEncrypted.exception.message"));
    }
    // Check if stream is PEM encoded
    PemInfo pemInfo = PemUtil.decode(new ByteArrayInputStream(streamContents));
    if (pemInfo != null) {
        // It is - get DER from PEM
        streamContents = pemInfo.getContent();
    }
    try {
        // Read OpenSSL DER structure
        ASN1InputStream asn1InputStream = new ASN1InputStream(streamContents);
        ASN1Primitive openSsl = asn1InputStream.readObject();
        asn1InputStream.close();
        if (openSsl instanceof ASN1Sequence) {
            ASN1Sequence seq = (ASN1Sequence) openSsl;
            if (seq.size() == 9) {
                // RSA private key
                BigInteger version = ((ASN1Integer) seq.getObjectAt(0)).getValue();
                BigInteger modulus = ((ASN1Integer) seq.getObjectAt(1)).getValue();
                BigInteger publicExponent = ((ASN1Integer) seq.getObjectAt(2)).getValue();
                BigInteger privateExponent = ((ASN1Integer) seq.getObjectAt(3)).getValue();
                BigInteger primeP = ((ASN1Integer) seq.getObjectAt(4)).getValue();
                BigInteger primeQ = ((ASN1Integer) seq.getObjectAt(5)).getValue();
                BigInteger primeExponentP = ((ASN1Integer) seq.getObjectAt(6)).getValue();
                BigInteger primeExponenetQ = ((ASN1Integer) seq.getObjectAt(7)).getValue();
                BigInteger crtCoefficient = ((ASN1Integer) seq.getObjectAt(8)).getValue();
                if (!version.equals(VERSION)) {
                    throw new CryptoException(MessageFormat.format(res.getString("OpenSslVersionIncorrect.exception.message"), "" + VERSION.intValue(), "" + version.intValue()));
                }
                RSAPrivateCrtKeySpec rsaPrivateCrtKeySpec = new RSAPrivateCrtKeySpec(modulus, publicExponent, privateExponent, primeP, primeQ, primeExponentP, primeExponenetQ, crtCoefficient);
                KeyFactory keyFactory = KeyFactory.getInstance("RSA");
                return keyFactory.generatePrivate(rsaPrivateCrtKeySpec);
            } else if (seq.size() == 6) {
                // DSA private key
                BigInteger version = ((ASN1Integer) seq.getObjectAt(0)).getValue();
                BigInteger primeModulusP = ((ASN1Integer) seq.getObjectAt(1)).getValue();
                BigInteger primeQ = ((ASN1Integer) seq.getObjectAt(2)).getValue();
                BigInteger generatorG = ((ASN1Integer) seq.getObjectAt(3)).getValue();
                // publicExponentY not req for pvk: sequence.getObjectAt(4);
                BigInteger secretExponentX = ((ASN1Integer) seq.getObjectAt(5)).getValue();
                if (!version.equals(VERSION)) {
                    throw new CryptoException(MessageFormat.format(res.getString("OpenSslVersionIncorrect.exception.message"), "" + VERSION.intValue(), "" + version.intValue()));
                }
                DSAPrivateKeySpec dsaPrivateKeySpec = new DSAPrivateKeySpec(secretExponentX, primeModulusP, primeQ, generatorG);
                KeyFactory keyFactory = KeyFactory.getInstance("DSA");
                return keyFactory.generatePrivate(dsaPrivateKeySpec);
            } else if (seq.size() >= 2) {
                // EC private key (RFC 5915)
                org.bouncycastle.asn1.sec.ECPrivateKey pKey = org.bouncycastle.asn1.sec.ECPrivateKey.getInstance(seq);
                AlgorithmIdentifier algId = new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, pKey.getParameters());
                PrivateKeyInfo privInfo = new PrivateKeyInfo(algId, pKey);
                return new JcaPEMKeyConverter().getPrivateKey(privInfo);
            } else {
                throw new CryptoException(MessageFormat.format(res.getString("OpenSslSequenceIncorrectSize.exception.message"), "" + seq.size()));
            }
        } else {
            throw new CryptoException(res.getString("OpenSslSequenceNotFound.exception.message"));
        }
    } catch (Exception ex) {
        throw new CryptoException(res.getString("NoLoadOpenSslPrivateKey.exception.message"), ex);
    }
}
Also used : RSAPrivateCrtKeySpec(java.security.spec.RSAPrivateCrtKeySpec) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) PemInfo(org.kse.utilities.pem.PemInfo) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) CryptoException(org.kse.crypto.CryptoException) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) DSAPrivateKeySpec(java.security.spec.DSAPrivateKeySpec) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) ByteArrayInputStream(java.io.ByteArrayInputStream) BigInteger(java.math.BigInteger) CryptoException(org.kse.crypto.CryptoException) ASN1Primitive(org.bouncycastle.asn1.ASN1Primitive) KeyFactory(java.security.KeyFactory) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo)

Example 40 with org.bouncycastle.asn1.x509

use of org.bouncycastle.asn1.x509 in project keystore-explorer by kaikramer.

the class Pkcs8Util method loadEncrypted.

/**
 * Load an encrypted PKCS #8 private key from the specified stream. The
 * encoding of the private key may be PEM or DER.
 *
 * @param is
 *            Stream load the encrypted private key from
 * @param password
 *            Password to decrypt
 * @return The private key
 * @throws PrivateKeyUnencryptedException
 *             If private key is unencrypted
 * @throws PrivateKeyPbeNotSupportedException
 *             If private key PBE algorithm is not supported
 * @throws CryptoException
 *             Problem encountered while loading the private key
 * @throws IOException
 *             If an I/O error occurred
 */
public static PrivateKey loadEncrypted(InputStream is, Password password) throws CryptoException, IOException {
    byte[] streamContents = ReadUtil.readFully(is);
    // Check PKCS#8 is encrypted
    EncryptionType encType = getEncryptionType(new ByteArrayInputStream(streamContents));
    if (encType == null) {
        // Not a valid PKCS #8 private key
        throw new CryptoException(res.getString("NotValidPkcs8.exception.message"));
    }
    if (encType == UNENCRYPTED) {
        throw new PrivateKeyUnencryptedException(res.getString("Pkcs8IsEncrypted.exception.message"));
    }
    // Check if stream is PEM encoded
    PemInfo pemInfo = PemUtil.decode(new ByteArrayInputStream(streamContents));
    byte[] encPvk = null;
    if (pemInfo != null) {
        // It is - get DER from PEM
        encPvk = pemInfo.getContent();
    }
    // If we haven't got the encrypted bytes via PEM then assume it is DER encoded
    if (encPvk == null) {
        encPvk = streamContents;
    }
    // try to read PKCS#8 info
    PKCS8EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = null;
    try {
        encryptedPrivateKeyInfo = new PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo.getInstance(encPvk));
    } catch (Exception e) {
        // Not a valid PKCS #8 private key
        throw new CryptoException(res.getString("NotValidPkcs8.exception.message"));
    }
    // decrypt and create PrivateKey object from ASN.1 structure
    try {
        InputDecryptorProvider decProv = new JceOpenSSLPKCS8DecryptorProviderBuilder().setProvider("BC").build(password.toCharArray());
        PrivateKeyInfo privateKeyInfo = encryptedPrivateKeyInfo.decryptPrivateKeyInfo(decProv);
        return new JcaPEMKeyConverter().getPrivateKey(privateKeyInfo);
    } catch (Exception ex) {
        throw new CryptoException(res.getString("NoLoadPkcs8PrivateKey.exception.message"), ex);
    }
}
Also used : InputDecryptorProvider(org.bouncycastle.operator.InputDecryptorProvider) ByteArrayInputStream(java.io.ByteArrayInputStream) PemInfo(org.kse.utilities.pem.PemInfo) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) JceOpenSSLPKCS8DecryptorProviderBuilder(org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo) CryptoException(org.kse.crypto.CryptoException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) CryptoException(org.kse.crypto.CryptoException) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) EncryptedPrivateKeyInfo(javax.crypto.EncryptedPrivateKeyInfo) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo)

Aggregations

IOException (java.io.IOException)81 X509Certificate (java.security.cert.X509Certificate)61 X500Name (org.bouncycastle.asn1.x500.X500Name)43 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)39 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)36 BigInteger (java.math.BigInteger)34 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)33 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)31 DEROctetString (org.bouncycastle.asn1.DEROctetString)31 DERIA5String (org.bouncycastle.asn1.DERIA5String)28 Date (java.util.Date)27 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)26 ArrayList (java.util.ArrayList)25 CertificateEncodingException (java.security.cert.CertificateEncodingException)24 CertificateException (java.security.cert.CertificateException)24 GeneralName (org.bouncycastle.asn1.x509.GeneralName)24 ByteArrayInputStream (java.io.ByteArrayInputStream)23 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)23 PrivateKey (java.security.PrivateKey)21 GeneralSecurityException (java.security.GeneralSecurityException)20