Search in sources :

Example 56 with ASN1Object

use of com.github.zhenwei.core.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.github.zhenwei.core.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.github.zhenwei.core.asn1.ASN1Object in project LinLong-Java by zhenwei1108.

the class CVCertificate method toASN1Primitive.

/**
 * @see com.github.zhenwei.core.asn1.ASN1Object#toASN1Primitive()
 */
public ASN1Primitive toASN1Primitive() {
    ASN1EncodableVector v = new ASN1EncodableVector(2);
    v.add(certificateBody);
    try {
        v.add(new DERApplicationSpecific(false, EACTags.STATIC_INTERNAL_AUTHENTIFICATION_ONE_STEP, new DEROctetString(signature)));
    } catch (IOException e) {
        throw new IllegalStateException("unable to convert signature!");
    }
    return new DERApplicationSpecific(EACTags.CARDHOLDER_CERTIFICATE, v);
}
Also used : DERApplicationSpecific(com.github.zhenwei.core.asn1.DERApplicationSpecific) ASN1EncodableVector(com.github.zhenwei.core.asn1.ASN1EncodableVector) IOException(java.io.IOException) DEROctetString(com.github.zhenwei.core.asn1.DEROctetString)

Example 59 with ASN1Object

use of com.github.zhenwei.core.asn1.ASN1Object in project LinLong-Java by zhenwei1108.

the class OERInputStream method parse.

public ASN1Object parse(OERDefinition.Element element) throws Exception {
    switch(element.baseType) {
        case SEQ_OF:
            {
                int l = readLength().intLength();
                // This l is the number of bytes that holds the actual length of the sequence of.
                byte[] lenEnc = allocateArray(l);
                if (Streams.readFully(this, lenEnc) != lenEnc.length) {
                    throw new IOException("could not read all of count of seq-of values");
                }
                // 
                // The actual number of elements encoded into this seq-of.
                // 
                int j = BigIntegers.fromUnsignedByteArray(lenEnc).intValue();
                debugPrint(element.appendLabel("(len = " + j + ")"));
                ASN1EncodableVector avec = new ASN1EncodableVector();
                for (int n = 0; n < j; n++) {
                    avec.add(parse(element.children.get(0)));
                }
                return new DERSequence(avec);
            }
        case SEQ:
            {
                Sequence sequence = sequence(countOptionalChildTypes(element), element.hasDefaultChildren(), element.extensionsInDefinition);
                debugPrint(element.appendLabel(sequence.toString()));
                ASN1EncodableVector avec = new ASN1EncodableVector();
                for (int t = 0; t < element.children.size(); t++) {
                    OERDefinition.Element child = element.children.get(t);
                    if (child.explicit) {
                        // debugPrint(child.appendLabel("E[" + t + "]"));
                        avec.add(parse(child));
                    } else {
                        if (sequence.hasOptional(element.optionalOrDefaultChildrenInOrder().indexOf(child))) {
                            // debugPrint(child.appendLabel("O[" + t + "]"));
                            avec.add(OEROptional.getInstance(parse(child)));
                        } else {
                            if (child.getDefaultValue() != null) {
                                avec.add(child.defaultValue);
                                debugPrint("Using default.");
                            } else {
                                avec.add(absent(child));
                            }
                        }
                    }
                }
                return new DERSequence(avec);
            }
        case CHOICE:
            {
                Choice choice = choice();
                debugPrint(element.appendLabel(choice.toString()));
                if (choice.isContextSpecific()) {
                    OERDefinition.Element item = element.children.get(choice.getTag());
                    return new DERTaggedObject(choice.tag, parse(element.children.get(choice.getTag())));
                } else if (choice.isApplicationTagClass()) {
                    throw new IllegalStateException("Unimplemented tag type");
                } else if (choice.isPrivateTagClass()) {
                    throw new IllegalStateException("Unimplemented tag type");
                } else if (choice.isUniversalTagClass()) {
                    switch(choice.getTag()) {
                    }
                } else {
                    throw new IllegalStateException("Unimplemented tag type");
                }
            }
        case ENUM:
            {
                BigInteger bi = enumeration();
                debugPrint(element.appendLabel("ENUM(" + bi + ") = " + element.children.get(bi.intValue()).label));
                return new ASN1Enumerated(bi);
            }
        case INT:
            {
                byte[] data;
                BigInteger bi;
                // 
                // Special fixed width cases used for signed and unsigned 8/16/24/32/64 bit numbers.
                // 
                int bytesToRead = element.intBytesForRange();
                if (// Fixed width
                bytesToRead != 0) {
                    data = allocateArray(Math.abs(bytesToRead));
                    Streams.readFully(this, data);
                    switch(data.length) {
                        case 1:
                            bi = BigInteger.valueOf(data[0]);
                            break;
                        case 2:
                            bi = BigInteger.valueOf(Pack.bigEndianToShort(data, 0));
                            break;
                        case 4:
                            bi = BigInteger.valueOf(Pack.bigEndianToInt(data, 0));
                            break;
                        case 8:
                            bi = BigInteger.valueOf(Pack.bigEndianToLong(data, 0));
                            break;
                        default:
                            throw new IllegalStateException("Unknown size");
                    }
                } else if (// INTEGER(0 ... MAX) or INTEGER (0 ... n)
                element.isLowerRangeZero()) {
                    LengthInfo lengthInfo = readLength();
                    data = allocateArray(lengthInfo.intLength());
                    Streams.readFully(this, data);
                    if (data.length == 0) {
                        bi = BigInteger.ZERO;
                    } else {
                        bi = BigIntegers.fromUnsignedByteArray(data);
                    }
                } else {
                    // 
                    // Classic twos compliment.
                    // 
                    LengthInfo lengthInfo = readLength();
                    data = allocateArray(lengthInfo.intLength());
                    Streams.readFully(this, data);
                    if (data.length == 0) {
                        bi = BigInteger.ZERO;
                    } else {
                        bi = new BigInteger(data);
                    }
                }
                if (debugOutput != null) {
                    debugPrint(element.appendLabel("INTEGER(" + data.length + " " + bi.toString(16) + ")"));
                }
                return new ASN1Integer(bi);
            }
        case OCTET_STRING:
            {
                byte[] data;
                int readSize = 0;
                if (element.upperBound != null && element.upperBound.equals(element.lowerBound)) {
                    // Fixed length there is no range.
                    readSize = element.upperBound.intValue();
                } else {
                    readSize = readLength().intLength();
                }
                data = allocateArray(readSize);
                if (Streams.readFully(this, data) != readSize) {
                    throw new IOException("did not read all of " + element.label);
                }
                if (debugOutput != null) {
                    debugPrint(element.appendLabel("OCTET STRING (" + data.length + ") = " + Hex.toHexString(data, 0, Math.min(data.length, 32))));
                }
                return new DEROctetString(data);
            }
        case UTF8_STRING:
            {
                // 27.3 and 27.4 a length determinant followed by a number of octets.
                byte[] data = allocateArray(readLength().intLength());
                if (Streams.readFully(this, data) != data.length) {
                    throw new IOException("could not read all of utf 8 string");
                }
                String content = Strings.fromUTF8ByteArray(data);
                if (debugOutput != null) {
                    debugPrint(element.appendLabel("UTF8 String (" + data.length + ") = " + content));
                }
                return new DERUTF8String(content);
            }
        case BIT_STRING:
            {
                byte[] data;
                if (element.isFixedLength()) {
                    data = new byte[element.lowerBound.intValue() / 8];
                } else if (BigInteger.ZERO.compareTo(element.upperBound) > 0) {
                    // Fixed size.
                    data = allocateArray(element.upperBound.intValue() / 8);
                } else {
                    // Length defined.
                    data = allocateArray(readLength().intLength() / 8);
                }
                Streams.readFully(this, data);
                if (debugOutput != null) {
                    StringBuffer sb = new StringBuffer();
                    sb.append("BIT STRING(" + (data.length * 8) + ") = ");
                    for (int i = 0; i != data.length; i++) {
                        byte b = data[i];
                        for (int t = 0; t < 8; t++) {
                            sb.append((b & 0x80) > 0 ? "1" : "0");
                            b <<= 1;
                        }
                    }
                    debugPrint(element.appendLabel(sb.toString()));
                }
                return new DERBitString(data);
            }
        case NULL:
            debugPrint(element.appendLabel("NULL"));
            return DERNull.INSTANCE;
        case EXTENSION:
            LengthInfo li = readLength();
            byte[] value = new byte[li.intLength()];
            if (Streams.readFully(this, value) != li.intLength()) {
                throw new IOException("could not read all of count of open value in choice (...) ");
            }
            debugPrint("ext " + li.intLength() + " " + Hex.toHexString(value));
            return new DEROctetString(value);
    }
    throw new IllegalStateException("Unhandled type " + element.baseType);
}
Also used : DERUTF8String(com.github.zhenwei.core.asn1.DERUTF8String) DERTaggedObject(com.github.zhenwei.core.asn1.DERTaggedObject) DERBitString(com.github.zhenwei.core.asn1.DERBitString) IOException(java.io.IOException) DERSequence(com.github.zhenwei.core.asn1.DERSequence) ASN1Integer(com.github.zhenwei.core.asn1.ASN1Integer) DEROctetString(com.github.zhenwei.core.asn1.DEROctetString) DERUTF8String(com.github.zhenwei.core.asn1.DERUTF8String) DERBitString(com.github.zhenwei.core.asn1.DERBitString) DEROctetString(com.github.zhenwei.core.asn1.DEROctetString) DERSequence(com.github.zhenwei.core.asn1.DERSequence) ASN1Enumerated(com.github.zhenwei.core.asn1.ASN1Enumerated) ASN1EncodableVector(com.github.zhenwei.core.asn1.ASN1EncodableVector) BigInteger(java.math.BigInteger)

Example 60 with ASN1Object

use of com.github.zhenwei.core.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)

Aggregations

IOException (java.io.IOException)37 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