Example usage for org.bouncycastle.asn1.pkcs PrivateKeyInfo parsePrivateKey

List of usage examples for org.bouncycastle.asn1.pkcs PrivateKeyInfo parsePrivateKey

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.pkcs PrivateKeyInfo parsePrivateKey.

Prototype

public ASN1Encodable parsePrivateKey() throws IOException 

Source Link

Usage

From source file:com.vvote.thirdparty.ximix.util.BLSKeyStore.java

License:Apache License

/**
 * Load the key store object from the passed in PKCS#12 encoding, using the passed in password.
 *
 * @param password the password to unlock the key store.
 * @param encoding the ASN.1 encoded bytes representing the PKCS#12 store.
 * @throws IOException on a parsing error.
 * @throws GeneralSecurityException if there's an exception decrypting the store.
 *//* w  w w .ja  v  a  2s. c  o m*/
public synchronized void load(char[] password, byte[] encoding) throws IOException, GeneralSecurityException {
    try {
        PKCS12PfxPdu pfx = new PKCS12PfxPdu(encoding);
        InputDecryptorProvider inputDecryptorProvider = new JcePKCSPBEInputDecryptorProviderBuilder()
                .setProvider("BC").build(password);
        ContentInfo[] infos = pfx.getContentInfos();

        for (int i = 0; i != infos.length; i++) {
            if (infos[i].getContentType().equals(PKCSObjectIdentifiers.encryptedData)) {
                PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i], inputDecryptorProvider);

                PKCS12SafeBag[] bags = dataFact.getSafeBags();

                Attribute[] attributes = bags[0].getAttributes();

                X509CertificateHolder cert = (X509CertificateHolder) bags[0].getBagValue();

                String keyID = getKeyID(attributes);
                BLS01PublicKeyParameters publicKeyParameters = BLSPublicKeyFactory
                        .createKey(cert.getSubjectPublicKeyInfo());

                paramsMap.put(keyID, publicKeyParameters.getParameters());
                sequenceNoMap.put(keyID, ASN1Integer.getInstance(
                        cert.getExtension(XimixObjectIdentifiers.ximixShareIdExtension).getParsedValue())
                        .getValue().intValue());
                sharedPublicKeyMap.put(keyID, publicKeyParameters.getPk());

                if (KeyUsage.fromExtensions(cert.getExtensions()).hasUsages(KeyUsage.digitalSignature)) {
                    signingKeys.add(keyID);
                }
            } else {
                PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i]);

                PKCS12SafeBag[] bags = dataFact.getSafeBags();
                String keyID = getKeyID(bags[0].getAttributes());

                PKCS8EncryptedPrivateKeyInfo encInfo = (PKCS8EncryptedPrivateKeyInfo) bags[0].getBagValue();
                PrivateKeyInfo info = encInfo.decryptPrivateKeyInfo(inputDecryptorProvider);

                sharedPrivateKeyMap.put(keyID, ASN1Integer.getInstance(info.parsePrivateKey()).getValue());
            }
        }
    } catch (PKCSException e) {
        throw new GeneralSecurityException("Unable to load key store: " + e.getMessage(), e);
    }
}

From source file:de.tsenger.animamea.ta.CertificateProvider.java

License:Open Source License

public ECPrivateKey getPrivateKey() throws IOException {
    ASN1Sequence pkSeq = null;/*  ww  w .j  a v  a2s . c o m*/
    pkSeq = (ASN1Sequence) ASN1Sequence.fromByteArray(pkBytes);

    PrivateKeyInfo pkInfo = new PrivateKeyInfo(pkSeq);
    ECPrivateKey ecpk = ECPrivateKey.getInstance(pkInfo.parsePrivateKey());
    return ecpk;
}

From source file:fr.insalyon.creatis.vip.core.server.business.proxy.ProxyClient.java

License:Open Source License

private void printKey(PrivateKey key, PrintStream out) throws IOException {
    out.println("-----BEGIN RSA PRIVATE KEY-----");
    ByteArrayInputStream inStream = new ByteArrayInputStream(key.getEncoded());
    ASN1InputStream derInputStream = new ASN1InputStream(inStream);
    ASN1Primitive keyInfo = derInputStream.readObject();
    PrivateKeyInfo pki;
    pki = PrivateKeyInfo.getInstance(keyInfo);
    ASN1Primitive innerType = pki.parsePrivateKey().toASN1Primitive();
    // build and return the actual key
    ASN1Sequence privKey = (ASN1Sequence) innerType;
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    DEROutputStream der = new DEROutputStream(bout);
    der.writeObject(privKey);//from   w w  w .  j a v  a2  s.c  om
    printB64(bout.toByteArray(), out);
    out.println("-----END RSA PRIVATE KEY-----");
}

From source file:okhttp3.tls.HeldCertificate.java

License:Apache License

private ByteString pkcs1Bytes() {
    try {//from w  ww. j av  a 2s.  com
        PrivateKeyInfo privateKeyInfo = PrivateKeyInfo.getInstance(keyPair.getPrivate().getEncoded());
        return ByteString.of(privateKeyInfo.parsePrivateKey().toASN1Primitive().getEncoded());
    } catch (IOException e) {
        throw new AssertionError(e);
    }
}

From source file:org.cryptoworkshop.ximix.node.crypto.key.BLSKeyManager.java

License:Apache License

public synchronized void load(char[] password, byte[] encoding) throws IOException, GeneralSecurityException {
    try {/*from   www . j ava2  s . c  o m*/
        PKCS12PfxPdu pfx = new PKCS12PfxPdu(encoding);
        InputDecryptorProvider inputDecryptorProvider = new JcePKCSPBEInputDecryptorProviderBuilder()
                .setProvider("BC").build(password);
        ContentInfo[] infos = pfx.getContentInfos();

        for (int i = 0; i != infos.length; i++) {
            if (infos[i].getContentType().equals(PKCSObjectIdentifiers.encryptedData)) {
                PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i], inputDecryptorProvider);

                PKCS12SafeBag[] bags = dataFact.getSafeBags();

                Attribute[] attributes = bags[0].getAttributes();

                X509CertificateHolder cert = (X509CertificateHolder) bags[0].getBagValue();

                String keyID = getKeyID(attributes);
                BLS01PublicKeyParameters publicKeyParameters = BLSPublicKeyFactory
                        .createKey(cert.getSubjectPublicKeyInfo());

                paramsMap.put(keyID, publicKeyParameters.getParameters());
                sharedPublicKeyMap.init(keyID, 1);
                sharedPublicKeyMap.addValue(keyID, new ElementShare(ASN1Integer.getInstance(
                        cert.getExtension(XimixObjectIdentifiers.ximixShareIdExtension).getParsedValue())
                        .getValue().intValue(), publicKeyParameters.getPk()));

                if (KeyUsage.fromExtensions(cert.getExtensions()).hasUsages(KeyUsage.digitalSignature)) {
                    signingKeys.add(keyID);
                }
            } else {
                PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i]);

                PKCS12SafeBag[] bags = dataFact.getSafeBags();
                String keyID = getKeyID(bags[0].getAttributes());

                PKCS8EncryptedPrivateKeyInfo encInfo = (PKCS8EncryptedPrivateKeyInfo) bags[0].getBagValue();
                PrivateKeyInfo info = encInfo.decryptPrivateKeyInfo(inputDecryptorProvider);

                sharedPrivateKeyMap.init(keyID, 1);
                sharedPrivateKeyMap.addValue(keyID,
                        new BigIntegerShare(sharedPublicKeyMap.getShare(keyID).getSequenceNo(),
                                ASN1Integer.getInstance(info.parsePrivateKey()).getValue()));
            }
        }
    } catch (PKCSException e) {
        throw new GeneralSecurityException("Unable to load key store: " + e.getMessage(), e);
    }
}

From source file:org.cryptoworkshop.ximix.node.crypto.key.ECKeyManager.java

License:Apache License

public synchronized void load(char[] password, byte[] encoding) throws IOException, GeneralSecurityException {
    try {/*from w  ww  . j a v  a2  s  .  co  m*/
        PKCS12PfxPdu pfx = new PKCS12PfxPdu(encoding);
        InputDecryptorProvider inputDecryptorProvider = new JcePKCSPBEInputDecryptorProviderBuilder()
                .setProvider("BC").build(password);
        ContentInfo[] infos = pfx.getContentInfos();

        for (int i = 0; i != infos.length; i++) {
            if (infos[i].getContentType().equals(PKCSObjectIdentifiers.encryptedData)) {
                PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i], inputDecryptorProvider);

                PKCS12SafeBag[] bags = dataFact.getSafeBags();

                Attribute[] attributes = bags[0].getAttributes();

                X509CertificateHolder cert = (X509CertificateHolder) bags[0].getBagValue();

                String keyID = getKeyID(attributes);
                ECPublicKeyParameters publicKeyParameters = (ECPublicKeyParameters) PublicKeyFactory
                        .createKey(cert.getSubjectPublicKeyInfo());

                paramsMap.put(keyID, publicKeyParameters.getParameters());
                sharedPublicKeyMap.init(keyID, 1);
                sharedPublicKeyMap.addValue(keyID, new ECPointShare(ASN1Integer.getInstance(
                        cert.getExtension(XimixObjectIdentifiers.ximixShareIdExtension).getParsedValue())
                        .getValue().intValue(), publicKeyParameters.getQ()));

                if (KeyUsage.fromExtensions(cert.getExtensions()).hasUsages(KeyUsage.digitalSignature)) {
                    signingKeys.add(keyID);
                }
            } else {
                PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i]);

                PKCS12SafeBag[] bags = dataFact.getSafeBags();
                String keyID = getKeyID(bags[0].getAttributes());

                PKCS8EncryptedPrivateKeyInfo encInfo = (PKCS8EncryptedPrivateKeyInfo) bags[0].getBagValue();
                PrivateKeyInfo info = encInfo.decryptPrivateKeyInfo(inputDecryptorProvider);

                sharedPrivateKeyMap.init(keyID, 1);
                sharedPrivateKeyMap.addValue(keyID,
                        new BigIntegerShare(sharedPublicKeyMap.getShare(keyID).getSequenceNo(),
                                ECPrivateKey.getInstance(info.parsePrivateKey()).getKey()));
            }
        }
    } catch (PKCSException e) {
        throw new GeneralSecurityException("Unable to load key store: " + e.getMessage(), e);
    }
}

From source file:org.jruby.ext.openssl.impl.pem.MiscPEMGenerator.java

License:Open Source License

private PemObject createPemObject(Object o) throws IOException {
    String type;/*  w ww. j  a v a  2  s . com*/
    byte[] encoding;

    if (o instanceof PemObject) {
        return (PemObject) o;
    }
    if (o instanceof PemObjectGenerator) {
        return ((PemObjectGenerator) o).generate();
    }
    if (o instanceof X509CertificateHolder) {
        type = "CERTIFICATE";
        encoding = ((X509CertificateHolder) o).getEncoded();
    } else if (o instanceof X509CRLHolder) {
        type = "X509 CRL";
        encoding = ((X509CRLHolder) o).getEncoded();
    } else if (o instanceof PrivateKeyInfo) {
        PrivateKeyInfo info = (PrivateKeyInfo) o;
        ASN1ObjectIdentifier algOID = info.getPrivateKeyAlgorithm().getAlgorithm();

        if (algOID.equals(PKCSObjectIdentifiers.rsaEncryption)) {
            type = "RSA PRIVATE KEY";
            encoding = info.parsePrivateKey().toASN1Primitive().getEncoded();
        } else if (algOID.equals(dsaOids[0]) || algOID.equals(dsaOids[1])) {
            type = "DSA PRIVATE KEY";

            DSAParameter p = DSAParameter.getInstance(info.getPrivateKeyAlgorithm().getParameters());
            ASN1EncodableVector v = new ASN1EncodableVector();

            v.add(new ASN1Integer(BigInteger.ZERO));
            v.add(new ASN1Integer(p.getP()));
            v.add(new ASN1Integer(p.getQ()));
            v.add(new ASN1Integer(p.getG()));

            BigInteger x = ASN1Integer.getInstance(info.parsePrivateKey()).getValue();
            BigInteger y = p.getG().modPow(x, p.getP());

            v.add(new ASN1Integer(y));
            v.add(new ASN1Integer(x));

            encoding = new DERSequence(v).getEncoded();
        } else if (algOID.equals(X9ObjectIdentifiers.id_ecPublicKey)) {
            type = "EC PRIVATE KEY";
            encoding = info.parsePrivateKey().toASN1Primitive().getEncoded();
        } else {
            throw new IOException("Cannot identify private key");
        }
    } else if (o instanceof SubjectPublicKeyInfo) {
        type = "PUBLIC KEY";
        encoding = ((SubjectPublicKeyInfo) o).getEncoded();
    } else if (o instanceof X509AttributeCertificateHolder) {
        type = "ATTRIBUTE CERTIFICATE";
        encoding = ((X509AttributeCertificateHolder) o).getEncoded();
    } else if (o instanceof PKCS10CertificationRequest) {
        type = "CERTIFICATE REQUEST";
        encoding = ((PKCS10CertificationRequest) o).getEncoded();
    } else if (o instanceof ContentInfo) {
        type = "PKCS7";
        encoding = ((ContentInfo) o).getEncoded();
    }
    //
    // NOTE: added behaviour to provide backwards compatibility with 1.47 :
    //
    else if (o instanceof java.security.cert.X509Certificate) // 1.47 compatibility
    {
        type = "CERTIFICATE";
        try {
            encoding = ((java.security.cert.X509Certificate) o).getEncoded();
        } catch (CertificateEncodingException e) {
            throw new PemGenerationException("Cannot encode object: " + e.toString());
        }
    } else if (o instanceof java.security.cert.X509CRL) // 1.47 compatibility
    {
        type = "X509 CRL";
        try {
            encoding = ((java.security.cert.X509CRL) o).getEncoded();
        } catch (CRLException e) {
            throw new PemGenerationException("Cannot encode object: " + e.toString());
        }
    } else if (o instanceof java.security.KeyPair) // 1.47 compatibility
    {
        return createPemObject(((java.security.KeyPair) o).getPrivate());
    } else if (o instanceof java.security.PrivateKey) // 1.47 compatibility
    {
        PrivateKeyInfo info = new PrivateKeyInfo(
                (ASN1Sequence) ASN1Primitive.fromByteArray(((java.security.Key) o).getEncoded()));

        if (o instanceof java.security.interfaces.RSAPrivateKey) {
            type = "RSA PRIVATE KEY";

            encoding = info.parsePrivateKey().toASN1Primitive().getEncoded();
        } else if (o instanceof java.security.interfaces.DSAPrivateKey) {
            type = "DSA PRIVATE KEY";

            DSAParameter p = DSAParameter.getInstance(info.getPrivateKeyAlgorithm().getParameters());
            ASN1EncodableVector v = new ASN1EncodableVector();

            v.add(new DERInteger(0));
            v.add(new DERInteger(p.getP()));
            v.add(new DERInteger(p.getQ()));
            v.add(new DERInteger(p.getG()));

            BigInteger x = ((java.security.interfaces.DSAPrivateKey) o).getX();
            BigInteger y = p.getG().modPow(x, p.getP());

            v.add(new DERInteger(y));
            v.add(new DERInteger(x));

            encoding = new DERSequence(v).getEncoded();
        } else if (((java.security.PrivateKey) o).getAlgorithm().equals("ECDSA")) {
            type = "EC PRIVATE KEY";

            encoding = info.parsePrivateKey().toASN1Primitive().getEncoded();
        } else {
            throw new IOException("Cannot identify private key");
        }
    } else if (o instanceof java.security.PublicKey) // 1.47 compatibility
    {
        type = "PUBLIC KEY";

        encoding = ((java.security.PublicKey) o).getEncoded();
    } else if (o instanceof X509AttributeCertificate) // 1.47 compatibility
    {
        type = "ATTRIBUTE CERTIFICATE";
        encoding = ((X509AttributeCertificate) o).getEncoded();
    }
    //
    //
    //
    else {
        throw new PemGenerationException("unknown object passed - can't encode.");
    }

    if (encryptor != null) // NEW STUFF (NOT IN OLD)
    {
        String dekAlgName = Strings.toUpperCase(encryptor.getAlgorithm());

        // Note: For backward compatibility
        if (dekAlgName.equals("DESEDE")) {
            dekAlgName = "DES-EDE3-CBC";
        }

        byte[] iv = encryptor.getIV();
        byte[] encData = encryptor.encrypt(encoding);

        List<PemHeader> headers = new ArrayList<PemHeader>(2);

        headers.add(new PemHeader("Proc-Type", "4,ENCRYPTED"));
        headers.add(new PemHeader("DEK-Info", dekAlgName + "," + getHexEncoded(iv)));

        return new PemObject(type, headers, encData);
    }
    return new PemObject(type, encoding);
}

From source file:org.jruby.ext.openssl.x509store.PEMInputOutput.java

License:LGPL

/**
 * c: PEM_read_PrivateKey + PEM_read_bio_PrivateKey
 * CAUTION: KeyPair#getPublic() may be null.
 *///from  ww  w. j  a  v a  2 s.  c  o m
public static KeyPair readPrivateKey(Reader in, char[] password) throws IOException {
    BufferedReader _in = makeBuffered(in);
    String line;
    while ((line = _in.readLine()) != null) {
        if (line.indexOf(BEF_G + PEM_STRING_RSA) != -1) {
            try {
                return readKeyPair(_in, password, "RSA", BEF_E + PEM_STRING_RSA);
            } catch (Exception e) {
                throw new IOException("problem creating RSA private key: " + e.toString());
            }
        } else if (line.indexOf(BEF_G + PEM_STRING_DSA) != -1) {
            try {
                return readKeyPair(_in, password, "DSA", BEF_E + PEM_STRING_DSA);
            } catch (Exception e) {
                throw new IOException("problem creating DSA private key: " + e.toString());
            }
        } else if (line.indexOf(BEF_G + PEM_STRING_ECPRIVATEKEY) != -1) {
            throw new IOException("EC private key not supported");
        } else if (line.indexOf(BEF_G + PEM_STRING_PKCS8INF) != -1) {
            try {
                byte[] bytes = readBytes(_in, 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 new IOException("problem creating private key: " + e.toString());
            }
        } else if (line.indexOf(BEF_G + PEM_STRING_PKCS8) != -1) {
            try {
                byte[] bytes = readBytes(_in, 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, password);
                } else {
                    privKey = derivePrivateKeyPBES1(eIn, algId, password);
                }
                return new KeyPair(null, privKey);
            } catch (Exception e) {
                throw new IOException("problem creating private key: " + e.toString());
            }
        }
    }
    return null;
}

From source file:org.soulwing.credo.service.crypto.jca.JcaPrivateKeyWrapper.java

License:Apache License

/**
 * {@inheritDoc}/*w  w w  . ja  v  a 2 s .c  om*/
 */
@Override
public String getContent() {
    try {
        PrivateKeyInfo keyInfo = PrivateKeyInfo.getInstance(delegate.getEncoded());
        byte[] content = keyInfo.parsePrivateKey().toASN1Primitive().getEncoded();
        return objectBuilderFactory.newBuilder().setType("RSA PRIVATE KEY").append(content).build()
                .getEncoded();
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.usrz.libs.crypto.pem.PEMFactory.java

License:Apache License

public PrivateKey getPrivateKey(PrivateKeyInfo keyInfo)
        throws NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException {

    final Object algorithmId = keyInfo.getPrivateKeyAlgorithm().getAlgorithm();
    final ASN1Encodable encodable;
    try {/*  ww w  .j ava2  s .  c o m*/
        encodable = keyInfo.parsePrivateKey();
    } catch (IOException exception) {
        throw new InvalidKeyException("Unable to parse private key structure", exception);
    }

    /* DSA keys */
    if (algorithmId.equals(X9ObjectIdentifiers.id_dsa)) {
        final ASN1Encodable encodedParams = keyInfo.getPrivateKeyAlgorithm().getParameters();
        final DSAParameter params = DSAParameter.getInstance(encodedParams);
        final BigInteger x = ASN1Integer.getInstance(encodable).getValue();
        return getDSAKeyFactory()
                .generatePrivate(new DSAPrivateKeySpec(x, params.getP(), params.getQ(), params.getG()));
    }

    /* RSA keys */
    if (algorithmId.equals(PKCSObjectIdentifiers.rsaEncryption)) {
        final RSAPrivateKey privateKey = RSAPrivateKey.getInstance(encodable);
        return getRSAKeyFactory().generatePrivate(
                new RSAPrivateCrtKeySpec(privateKey.getModulus(), privateKey.getPublicExponent(),
                        privateKey.getPrivateExponent(), privateKey.getPrime1(), privateKey.getPrime2(),
                        privateKey.getExponent1(), privateKey.getExponent2(), privateKey.getCoefficient()));
    }

    /* Others? */
    throw new NoSuchAlgorithmException("Unsupported algorithm for private key: " + algorithmId);

}