Example usage for org.bouncycastle.asn1.pkcs EncryptedPrivateKeyInfo getEncryptedData

List of usage examples for org.bouncycastle.asn1.pkcs EncryptedPrivateKeyInfo getEncryptedData

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.pkcs EncryptedPrivateKeyInfo getEncryptedData.

Prototype

public byte[] getEncryptedData() 

Source Link

Usage

From source file:edu.vt.middleware.crypt.io.PrivateKeyCredentialReader.java

License:Open Source License

/**
 * Decrypts a DER-encoded private key in PKCS#8 format.
 *
 * @param  encrypted  Bytes of DER-encoded encrypted private key.
 * @param  password  Password to decrypt private key.
 *
 * @return  ASN.1 encoded bytes of decrypted key.
 *
 * @throws  CryptException  On key decryption errors.
 *///from  w ww .j a  v  a  2s  .co  m
private byte[] decryptPKCS8Key(final byte[] encrypted, final char[] password) throws CryptException {
    final EncryptionScheme scheme;
    try {
        final EncryptedPrivateKeyInfo ki = EncryptedPrivateKeyInfo
                .getInstance(ASN1Object.fromByteArray(encrypted));
        final AlgorithmIdentifier alg = ki.getEncryptionAlgorithm();
        if (PKCSObjectIdentifiers.id_PBES2.equals(alg.getObjectId())) {
            // PBES2 has following parameters:
            // {
            // {id-PBKDF2, {salt, iterationCount, keyLength (optional)}}
            // {encryptionAlgorithmOid, iv}
            // }
            final DERSequence pbeSeq = (DERSequence) alg.getParameters();
            final PBKDF2Parameters kdfParms = PBKDF2Parameters.decode((DERSequence) pbeSeq.getObjectAt(0));
            final PBES2CipherGenerator cipherGen = new PBES2CipherGenerator(
                    (DERSequence) pbeSeq.getObjectAt(1));
            if (kdfParms.getLength() == 0) {
                kdfParms.setLength(cipherGen.getKeySize() / 8);
            }
            scheme = new PBES2EncryptionScheme(cipherGen.generate(), kdfParms);
        } else {
            // Use PBES1 encryption scheme to decrypt key
            scheme = new PBES1EncryptionScheme(PBES1Algorithm.fromOid(alg.getObjectId().getId()),
                    PBEParameter.decode((DERSequence) alg.getParameters()));
        }
        return scheme.decrypt(password, ki.getEncryptedData());
    } catch (Exception e) {
        throw new CryptException("Failed decrypting PKCS#8 private key", e);
    }
}

From source file:org.cryptacular.asn.PKCS8PrivateKeyDecoder.java

License:Open Source License

@Override
protected byte[] decryptKey(final byte[] encrypted, final char[] password) {
    final EncryptionScheme scheme;
    final EncryptedPrivateKeyInfo ki = EncryptedPrivateKeyInfo.getInstance(tryConvertPem(encrypted));
    final AlgorithmIdentifier alg = ki.getEncryptionAlgorithm();
    if (PKCSObjectIdentifiers.id_PBES2.equals(alg.getAlgorithm())) {
        scheme = new PBES2EncryptionScheme(PBES2Parameters.getInstance(alg.getParameters()), password);
    } else {//from w w w.  jav a2  s  .  c  om
        scheme = new PBES1EncryptionScheme(PBES1Algorithm.fromOid(alg.getAlgorithm().getId()),
                PBEParameter.getInstance(alg.getParameters()), password);
    }
    return scheme.decrypt(ki.getEncryptedData());
}

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

License:LGPL

/**
 * c: PEM_read_PrivateKey + PEM_read_bio_PrivateKey
 * CAUTION: KeyPair#getPublic() may be null.
 *///w w w  .  j  av  a  2 s.c  om
@Override
public 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);
                ByteArrayInputStream bIn = new ByteArrayInputStream(bytes);
                ASN1InputStream aIn = new ASN1InputStream(bIn);
                PrivateKeyInfo info = new PrivateKeyInfo((ASN1Sequence) aIn.readObject());
                String type = getPrivateKeyTypeFromObjectId(info.getAlgorithmId().getObjectId());
                return readPrivateKeySequence(info.getPrivateKey().getDEREncoded(), 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);
                ByteArrayInputStream bIn = new ByteArrayInputStream(bytes);
                ASN1InputStream aIn = new ASN1InputStream(bIn);
                org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo eIn = new org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo(
                        (ASN1Sequence) aIn.readObject());
                AlgorithmIdentifier algId = eIn.getEncryptionAlgorithm();
                String algorithm = ASN1Registry.o2a(algId.getObjectId());
                algorithm = (algorithm.split("-"))[0];
                PKCS12PBEParams pbeParams = new PKCS12PBEParams((ASN1Sequence) algId.getParameters());
                SecretKeyFactory fact = OpenSSLReal.getSecretKeyFactoryBC(algorithm); // need to use BC for PKCS12PBEParams.
                PBEKeySpec pbeSpec = new PBEKeySpec(password);
                SecretKey key = fact.generateSecret(pbeSpec);
                PBEParameterSpec defParams = new PBEParameterSpec(pbeParams.getIV(),
                        pbeParams.getIterations().intValue());
                Cipher cipher = OpenSSLReal.getCipherBC(algorithm); // need to use BC for PBEParameterSpec.
                cipher.init(Cipher.UNWRAP_MODE, key, defParams);
                // wrappedKeyAlgorithm is unknown ("")
                PrivateKey privKey = (PrivateKey) cipher.unwrap(eIn.getEncryptedData(), "", Cipher.PRIVATE_KEY);
                return new KeyPair(null, privKey);
            } catch (Exception e) {
                throw new IOException("problem creating private key: " + e.toString());
            }
        }
    }
    return null;
}

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

License:LGPL

private static PrivateKey derivePrivateKeyPBES1(EncryptedPrivateKeyInfo eIn, AlgorithmIdentifier algId,
        char[] password) throws GeneralSecurityException, IOException {
    // From BC's PEMReader
    PKCS12PBEParams pkcs12Params = PKCS12PBEParams.getInstance(algId.getParameters());
    PBEKeySpec pbeSpec = new PBEKeySpec(password);
    PBEParameterSpec pbeParams = new PBEParameterSpec(pkcs12Params.getIV(),
            pkcs12Params.getIterations().intValue());

    //String algorithm = algId.getAlgorithm().getId();
    String algorithm = ASN1Registry.o2a(algId.getAlgorithm());
    algorithm = (algorithm.split("-"))[0];

    SecretKeyFactory secKeyFact = SecretKeyFactory.getInstance(algorithm);

    Cipher cipher = Cipher.getInstance(algorithm);

    cipher.init(Cipher.DECRYPT_MODE, secKeyFact.generateSecret(pbeSpec), pbeParams);

    PrivateKeyInfo pInfo = PrivateKeyInfo
            .getInstance(ASN1Primitive.fromByteArray(cipher.doFinal(eIn.getEncryptedData())));
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pInfo.getEncoded());

    String keyFactAlg = ASN1Registry.o2a(pInfo.getPrivateKeyAlgorithm().getAlgorithm());

    // TODO: Can we just set it to RSA as in derivePrivateKeyPBES2?
    KeyFactory keyFact;/*  w w w.ja v a2  s.  c  om*/
    if (keyFactAlg.startsWith("dsa")) {
        keyFact = KeyFactory.getInstance("DSA");
    } else {
        keyFact = KeyFactory.getInstance("RSA");
    }

    return keyFact.generatePrivate(keySpec);
}

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

License:LGPL

private static PrivateKey derivePrivateKeyPBES2(EncryptedPrivateKeyInfo eIn, AlgorithmIdentifier algId,
        char[] password) throws GeneralSecurityException, InvalidCipherTextException {
    PBES2Parameters pbeParams = PBES2Parameters.getInstance((ASN1Sequence) algId.getParameters());
    CipherParameters cipherParams = extractPBES2CipherParams(password, pbeParams);

    EncryptionScheme scheme = pbeParams.getEncryptionScheme();
    BufferedBlockCipher cipher;/*from  ww  w  .j  a  v a2 s.  c  om*/
    if (scheme.getAlgorithm().equals(PKCSObjectIdentifiers.RC2_CBC)) {
        RC2CBCParameter rc2Params = RC2CBCParameter.getInstance(scheme);
        byte[] iv = rc2Params.getIV();
        CipherParameters param = new ParametersWithIV(cipherParams, iv);
        cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new RC2Engine()));
        cipher.init(false, param);
    } else {
        byte[] iv = ((ASN1OctetString) scheme.getObject()).getOctets();
        // this version, done for BC 1.49 compat, caused #1238.
        //            byte[] iv = ASN1OctetString.getInstance(scheme).getOctets();
        CipherParameters param = new ParametersWithIV(cipherParams, iv);
        cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new DESedeEngine()));
        cipher.init(false, param);
    }

    byte[] data = eIn.getEncryptedData();
    byte[] out = new byte[cipher.getOutputSize(data.length)];
    int len = cipher.processBytes(data, 0, data.length, out, 0);
    len += cipher.doFinal(out, len);
    byte[] pkcs8 = new byte[len];
    System.arraycopy(out, 0, pkcs8, 0, len);
    KeyFactory fact = KeyFactory.getInstance("RSA"); // It seems to work for both RSA and DSA.
    return fact.generatePrivate(new PKCS8EncodedKeySpec(pkcs8));
}

From source file:org.xwiki.crypto.password.internal.DefaultPrivateKeyPasswordBasedEncryptor.java

License:Open Source License

@Override
public PrivateKeyParameters decrypt(byte[] password, byte[] encoded)
        throws GeneralSecurityException, IOException {
    EncryptedPrivateKeyInfo encKeyInfo = EncryptedPrivateKeyInfo.getInstance(encoded);
    return decrypt(password, encKeyInfo.getEncryptionAlgorithm(), encKeyInfo.getEncryptedData());
}