Search in sources :

Example 56 with ASN1Object

use of com.mindbright.asn1.ASN1Object in project jruby-openssl by jruby.

the class PEMInputOutput method readPrivateKey.

/**
 * c: PEM_read_PrivateKey + PEM_read_bio_PrivateKey
 * CAUTION: KeyPair#getPublic() may be null.
 */
public static KeyPair readPrivateKey(final Reader in, char[] passwd) throws PasswordRequiredException, IOException {
    final String BEG_STRING_ECPRIVATEKEY = BEF_G + PEM_STRING_ECPRIVATEKEY;
    final String BEG_STRING_PKCS8INF = BEF_G + PEM_STRING_PKCS8INF;
    final String BEG_STRING_PKCS8 = BEF_G + PEM_STRING_PKCS8;
    final BufferedReader reader = makeBuffered(in);
    String line;
    while ((line = reader.readLine()) != null) {
        if (line.indexOf(BEG_STRING_RSA) != -1) {
            try {
                return readKeyPair(reader, passwd, "RSA", BEF_E + PEM_STRING_RSA);
            } catch (Exception e) {
                throw mapReadException("problem creating RSA private key: ", e);
            }
        } else if (line.indexOf(BEG_STRING_DSA) != -1) {
            try {
                return readKeyPair(reader, passwd, "DSA", BEF_E + PEM_STRING_DSA);
            } catch (Exception e) {
                throw mapReadException("problem creating DSA private key: ", e);
            }
        } else if (line.indexOf(BEG_STRING_ECPRIVATEKEY) != -1) {
            try {
                return readKeyPair(reader, passwd, "ECDSA", BEF_E + PEM_STRING_ECPRIVATEKEY);
            } catch (Exception e) {
                throw mapReadException("problem creating DSA private key: ", e);
            }
        } else if (line.indexOf(BEG_STRING_PKCS8INF) != -1) {
            try {
                byte[] bytes = readBase64Bytes(reader, BEF_E + PEM_STRING_PKCS8INF);
                PrivateKeyInfo info = PrivateKeyInfo.getInstance(bytes);
                String type = getPrivateKeyTypeFromObjectId(info.getPrivateKeyAlgorithm().getAlgorithm());
                return org.jruby.ext.openssl.impl.PKey.readPrivateKey(((ASN1Object) info.parsePrivateKey()).getEncoded(ASN1Encoding.DER), type);
            } catch (Exception e) {
                throw mapReadException("problem creating private key: ", e);
            }
        } else if (line.indexOf(BEG_STRING_PKCS8) != -1) {
            try {
                byte[] bytes = readBase64Bytes(reader, BEF_E + PEM_STRING_PKCS8);
                EncryptedPrivateKeyInfo eIn = EncryptedPrivateKeyInfo.getInstance(bytes);
                AlgorithmIdentifier algId = eIn.getEncryptionAlgorithm();
                PrivateKey privKey;
                if (algId.getAlgorithm().toString().equals("1.2.840.113549.1.5.13")) {
                    // PBES2
                    privKey = derivePrivateKeyPBES2(eIn, algId, passwd);
                } else {
                    privKey = derivePrivateKeyPBES1(eIn, algId, passwd);
                }
                return new KeyPair(null, privKey);
            } catch (Exception e) {
                throw mapReadException("problem creating private key: ", e);
            }
        }
    }
    return null;
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) ECPrivateKey(java.security.interfaces.ECPrivateKey) BufferedReader(java.io.BufferedReader) EncryptedPrivateKeyInfo(org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) DEROctetString(org.bouncycastle.asn1.DEROctetString) ASN1Object(org.bouncycastle.asn1.ASN1Object) GeneralSecurityException(java.security.GeneralSecurityException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) CertificateEncodingException(java.security.cert.CertificateEncodingException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) CMSException(org.bouncycastle.cms.CMSException) InvalidCipherTextException(org.bouncycastle.crypto.InvalidCipherTextException) IOException(java.io.IOException) CRLException(java.security.cert.CRLException) CertificateException(java.security.cert.CertificateException) EncryptedPrivateKeyInfo(org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier)

Example 57 with ASN1Object

use of com.mindbright.asn1.ASN1Object in project tbd-studio-se by Talend.

the class MongoDBConnectionUtil method buildSSLContext_PEM.

private static SSLContext buildSSLContext_PEM(String _keystore, String _keystorePass, String _truststore, String _truststorePass, SSLContext sslContext) {
    SSLContext context = null;
    final String pubCertEndDelimiter = "-----END CERTIFICATE-----";
    final String privateKeyStartDelimiter = "-----BEGIN PRIVATE KEY-----";
    final String privateKeyEndDelimiter = "-----END PRIVATE KEY-----";
    final String privateKeyRSAStartDelimiter = "-----BEGIN RSA PRIVATE KEY-----";
    final String privateKeyRSAEndDelimiter = "-----END RSA PRIVATE KEY-----";
    try {
        context = SSLContext.getInstance("TLS");
        byte[] certAndKey = Files.readAllBytes(Paths.get(new File(_keystore).toURI()));
        String[] tokens = new String(certAndKey).split(pubCertEndDelimiter);
        byte[] certBytes = tokens[0].concat(pubCertEndDelimiter).getBytes();
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        java.security.cert.Certificate certificate = certificateFactory.generateCertificate(new ByteArrayInputStream(certBytes));
        // 
        X509Certificate cert = (X509Certificate) certificate;
        PrivateKey key = null;
        KeyFactory kf = KeyFactory.getInstance("RSA");
        if (tokens[1].contains(privateKeyStartDelimiter)) {
            byte[] privatekeyBytes = tokens[1].replace(privateKeyStartDelimiter, "").replace(privateKeyEndDelimiter, "").replace("\r\n", "").replace("\n", "").getBytes();
            byte[] decode = Base64.getDecoder().decode(privatekeyBytes);
            PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decode);
            key = kf.generatePrivate(spec);
        } else if (tokens[1].contains(privateKeyRSAStartDelimiter)) {
            byte[] privateKeyBytes = tokens[1].replace(privateKeyRSAStartDelimiter, "").replace(privateKeyRSAEndDelimiter, "").replace("\r\n", "").replace("\n", "").getBytes("UTF-8");
            byte[] decodeBytes = Base64.getDecoder().decode(privateKeyBytes);
            ASN1Object fromByteArray = ASN1Sequence.fromByteArray(decodeBytes);
            RSAPrivateKeyStructure asn1PrivKey = new RSAPrivateKeyStructure((ASN1Sequence) fromByteArray);
            RSAPrivateKeySpec rsaPrivKeySpec = new RSAPrivateKeySpec(asn1PrivKey.getModulus(), asn1PrivKey.getPrivateExponent());
            key = kf.generatePrivate(rsaPrivKeySpec);
        }
        KeyStore keystore = KeyStore.getInstance("JKS");
        keystore.load(null);
        keystore.setCertificateEntry("cert-alias", cert);
        keystore.setKeyEntry("key-alias", key, "changeit".toCharArray(), new Certificate[] { cert });
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(keystore, "changeit".toCharArray());
        KeyManager[] km = kmf.getKeyManagers();
        context.init(km, null, null);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return context;
}
Also used : PrivateKey(java.security.PrivateKey) SSLContext(javax.net.ssl.SSLContext) CertificateFactory(java.security.cert.CertificateFactory) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) NoSQLReflectionException(org.talend.repository.nosql.exceptions.NoSQLReflectionException) NoSQLServerException(org.talend.repository.nosql.exceptions.NoSQLServerException) JSONException(org.talend.utils.json.JSONException) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) Certificate(java.security.cert.Certificate) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) RSAPrivateKeySpec(java.security.spec.RSAPrivateKeySpec) ByteArrayInputStream(java.io.ByteArrayInputStream) RSAPrivateKeyStructure(org.bouncycastle.asn1.pkcs.RSAPrivateKeyStructure) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) ASN1Object(org.bouncycastle.asn1.ASN1Object) File(java.io.File) KeyManager(javax.net.ssl.KeyManager) KeyFactory(java.security.KeyFactory)

Example 58 with ASN1Object

use of com.mindbright.asn1.ASN1Object in project laverca by laverca.

the class CmsSignature method bytesToPkcs7SignedData.

/**
 * Convert a byte array to a PKCS7 SignedData object
 * @param bytes byte array
 * @return PKCS7 SignedData object
 */
public static SignedData bytesToPkcs7SignedData(byte[] bytes) {
    if (bytes == null) {
        throw new IllegalArgumentException("null bytes");
    }
    ASN1InputStream ais = new ASN1InputStream(bytes);
    ASN1Object asn1 = null;
    try {
        asn1 = ais.readObject();
    } catch (IOException ioe) {
        throw new IllegalArgumentException("not a pkcs7 signature");
    } finally {
        try {
            ais.close();
        } catch (IOException e) {
        // Ignore
        }
    }
    ContentInfo ci = ContentInfo.getInstance(asn1);
    ASN1ObjectIdentifier typeId = ci.getContentType();
    if (!typeId.equals(PKCSObjectIdentifiers.signedData)) {
        throw new IllegalArgumentException("not a pkcs7 signature");
    }
    return SignedData.getInstance(ci.getContent());
}
Also used : ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) ContentInfo(org.bouncycastle.asn1.pkcs.ContentInfo) IOException(java.io.IOException) ASN1Object(org.bouncycastle.asn1.ASN1Object) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 59 with ASN1Object

use of com.mindbright.asn1.ASN1Object in project documentproduction by qld-gov-au.

the class CertInformationCollector method addTimestampCerts.

/**
 * Processes an embedded signed timestamp, that has been placed into a signature. The
 * certificates and its chain(s) will be processed the same way as the signature itself.
 *
 * @param signerInformation of the signature, to get unsigned attributes from it.
 * @throws IOException
 * @throws CertificateProccessingException
 */
private void addTimestampCerts(SignerInformation signerInformation) throws IOException, CertificateProccessingException {
    AttributeTable unsignedAttributes = signerInformation.getUnsignedAttributes();
    if (unsignedAttributes == null) {
        return;
    }
    Attribute tsAttribute = unsignedAttributes.get(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken);
    if (tsAttribute == null) {
        return;
    }
    ASN1Encodable obj0 = tsAttribute.getAttrValues().getObjectAt(0);
    if (!(obj0 instanceof ASN1Object)) {
        return;
    }
    ASN1Object tsSeq = (ASN1Object) obj0;
    try {
        CMSSignedData signedData = new CMSSignedData(tsSeq.getEncoded("DER"));
        rootCertInfo.setTsaCerts(new CertSignatureInformation());
        processSignerStore(signedData, rootCertInfo.getTsaCerts());
    } catch (CMSException e) {
        throw new IOException("Error parsing timestamp token", e);
    }
}
Also used : Attribute(org.bouncycastle.asn1.cms.Attribute) AttributeTable(org.bouncycastle.asn1.cms.AttributeTable) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) IOException(java.io.IOException) ASN1Object(org.bouncycastle.asn1.ASN1Object) CMSSignedData(org.bouncycastle.cms.CMSSignedData) CMSException(org.bouncycastle.cms.CMSException)

Example 60 with ASN1Object

use of com.mindbright.asn1.ASN1Object in project OpenUnison by TremoloSecurity.

the class AndroidKeyStoreAttestation method getKeyDescriptionSequence.

private static ASN1Sequence getKeyDescriptionSequence(ASN1OctetString octet) throws CertificateParsingException {
    // Read out the Sequence
    ASN1Object asn1Object = X509ExtensionParsingUtil.getAsn1Object(octet.getOctets());
    if (asn1Object == null || !(asn1Object instanceof ASN1Sequence)) {
        throw new CertificateParsingException("Expected KeyDescription Sequence.");
    }
    ASN1Sequence sequence = (ASN1Sequence) asn1Object;
    if (sequence.size() != DESCRIPTION_LENGTH) {
        throw new CertificateParsingException("KeyDescription Sequence has " + sequence.size() + " elements.  Expected " + DESCRIPTION_LENGTH + " elements ");
    }
    return sequence;
}
Also used : ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) CertificateParsingException(java.security.cert.CertificateParsingException) ASN1Object(org.bouncycastle.asn1.ASN1Object)

Aggregations

IOException (java.io.IOException)35 Asn1Object (com.android.hotspot2.asn1.Asn1Object)25 ASN1Object (org.bouncycastle.asn1.ASN1Object)20 ArrayList (java.util.ArrayList)16 Asn1Constructed (com.android.hotspot2.asn1.Asn1Constructed)15 HashMap (java.util.HashMap)15 Asn1Object (io.churchkey.asn1.Asn1Object)13 DerParser (io.churchkey.asn1.DerParser)12 X509Certificate (java.security.cert.X509Certificate)12 Asn1Integer (com.android.hotspot2.asn1.Asn1Integer)10 DERBitString (com.android.org.bouncycastle.asn1.DERBitString)10 DERIA5String (com.android.org.bouncycastle.asn1.DERIA5String)10 DERPrintableString (com.android.org.bouncycastle.asn1.DERPrintableString)10 ByteBuffer (java.nio.ByteBuffer)10 Key (io.churchkey.Key)8 ByteArrayInputStream (java.io.ByteArrayInputStream)7 I18Name (com.android.anqp.I18Name)5 Asn1Oid (com.android.hotspot2.asn1.Asn1Oid)5 Asn1String (com.android.hotspot2.asn1.Asn1String)5 OidMappings (com.android.hotspot2.asn1.OidMappings)5