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

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

Introduction

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

Prototype

public AlgorithmIdentifier getPrivateKeyAlgorithm() 

Source Link

Usage

From source file:com.android.signapk.SignApk.java

License:Apache License

/** Read a PKCS#8 format private key. */
private static PrivateKey readPrivateKey(File file) throws IOException, GeneralSecurityException {
    DataInputStream input = new DataInputStream(new FileInputStream(file));
    try {/*from   www.  j  av a  2  s  .  c o m*/
        byte[] bytes = new byte[(int) file.length()];
        input.read(bytes);

        /* Check to see if this is in an EncryptedPrivateKeyInfo structure. */
        PKCS8EncodedKeySpec spec = decryptPrivateKey(bytes, file);
        if (spec == null) {
            spec = new PKCS8EncodedKeySpec(bytes);
        }

        /*
         * Now it's in a PKCS#8 PrivateKeyInfo structure. Read its Algorithm
         * OID and use that to construct a KeyFactory.
         */
        ASN1InputStream bIn = new ASN1InputStream(new ByteArrayInputStream(spec.getEncoded()));
        PrivateKeyInfo pki = PrivateKeyInfo.getInstance(bIn.readObject());
        String algOid = pki.getPrivateKeyAlgorithm().getAlgorithm().getId();

        return KeyFactory.getInstance(algOid).generatePrivate(spec);
    } finally {
        input.close();
    }
}

From source file:com.leon.utils.sign.v2.SignApk.java

License:Apache License

/** Read a PKCS#8 format private key. */
private static PrivateKey readPrivateKey(File file) throws IOException, GeneralSecurityException {
    DataInputStream input = new DataInputStream(new FileInputStream(file));
    try {//from w  w  w . jav a  2 s.c o m
        byte[] bytes = new byte[(int) file.length()];
        input.read(bytes);

        /* Check to see if this is in an EncryptedPrivateKeyInfo structure. */
        PKCS8EncodedKeySpec spec = decryptPrivateKey(bytes, file);
        if (spec == null) {
            spec = new PKCS8EncodedKeySpec(bytes);
        }

        /*
         * Now it's in a PKCS#8 PrivateKeyInfo structure. Read its Algorithm
         * OID and use that to construct a KeyFactory.
         */
        PrivateKeyInfo pki;
        try (ASN1InputStream bIn = new ASN1InputStream(new ByteArrayInputStream(spec.getEncoded()))) {
            pki = PrivateKeyInfo.getInstance(bIn.readObject());
        }
        String algOid = pki.getPrivateKeyAlgorithm().getAlgorithm().getId();

        return KeyFactory.getInstance(algOid).generatePrivate(spec);
    } finally {
        input.close();
    }
}

From source file:de.carne.certmgr.store.provider.bouncycastle.PKCS12Decoder.java

License:Open Source License

public void decodeKeyBag(PrivateKeyInfo bagValue, Attribute[] bagAttributes) {
    try {/*from w w w . j  av  a  2  s . c o m*/
        KeyFactory keyFactory = KeyFactory.getInstance(bagValue.getPrivateKeyAlgorithm().getAlgorithm().getId(),
                BouncyCastleProvider.PROVIDER_NAME);
        PrivateKey privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(bagValue.getEncoded()));

        for (Attribute bagAttribute : bagAttributes) {
            if (bagAttribute.getAttrType().equals(PKCS12SafeBag.localKeyIdAttribute)) {
                decodeKey(bagAttribute.getAttributeValues()[0], privateKey);
                break;
            }
        }
    } catch (Exception e) {
        LOG.info(e, null, "Unable to decode key data from PKCS#12 bag");
    }
}

From source file:de.tsenger.sandbox.PKCS8PrivateKey.java

License:Open Source License

public static void main(String[] args) throws IOException {
    byte[] pkBytes = readBinaryFile(
            "/home/tsenger/Dokumente/Programming/animamea/certs/Key_DEATTIDBSIDE003.pkcs8");

    DERSequence pkSeq = (DERSequence) DERSequence.fromByteArray(pkBytes);

    PrivateKeyInfo pkInfo = new PrivateKeyInfo(pkSeq);

    AlgorithmIdentifier ecPublicKey = pkInfo.getPrivateKeyAlgorithm();
    System.out.println(ecPublicKey.getAlgorithm().toString());
    System.out.println(HexString.bufferToHex(ecPublicKey.getEncoded(null)));

    X9ECParameters ecp = X9ECParameters.getInstance(ecPublicKey.getParameters());

    System.out.println("N: \n" + HexString.bufferToHex(Converter.bigIntToByteArray(ecp.getN())));

    ECPrivateKey ecpk2 = ECPrivateKey.getInstance(ecPublicKey);
    //ECPrivateKey.getInstance(pkInfo.getPrivateKey());
    System.out.println("private Key: \n" + HexString.bufferToHex(Converter.bigIntToByteArray(ecpk2.getKey())));

}

From source file:org.cesecore.keys.util.KeyToolsTest.java

License:Open Source License

@Test
public void testGenKeysECDSAx9() throws Exception {
    KeyPair keys = KeyTools.genKeys("prime192v1", AlgorithmConstants.KEYALGORITHM_ECDSA);
    // Verify that the keys are using maned curves, and not explicit parameters
    PrivateKeyInfo priv2 = PrivateKeyInfo.getInstance(keys.getPrivate().getEncoded());
    assertTrue("Private key is not encoded with named curves, but using explicit parameters",
            X962Parameters.getInstance(priv2.getPrivateKeyAlgorithm().getParameters()).isNamedCurve());
    SubjectPublicKeyInfo pub2 = SubjectPublicKeyInfo.getInstance(keys.getPublic().getEncoded());
    assertTrue("Public key is not encoded with named curves, but using explicit parameters",
            X962Parameters.getInstance(pub2.getAlgorithm().getParameters()).isNamedCurve());

    assertNotNull("keys must not be null", keys);
    String b64private = new String(Base64.encode(keys.getPrivate().getEncoded()));
    assertNotNull("b64private must not be null", b64private);
    // log.debug(b64private);
    X509Certificate cert = CertTools.genSelfCert("C=SE,O=Test,CN=Test", 365, null, keys.getPrivate(),
            keys.getPublic(), AlgorithmConstants.SIGALG_SHA256_WITH_ECDSA, true);
    // log.debug(cert);
    assertNotNull("cert must not be null", cert);
    String b64cert = new String(Base64.encode(cert.getEncoded()));
    assertNotNull("b64cert cannot be null", b64cert);
    // log.debug(b64cert);
    KeyTools.testKey(keys.getPrivate(), keys.getPublic(), "BC");
    // Test that fails
    KeyPair keys1 = KeyTools.genKeys("prime192v1", AlgorithmConstants.KEYALGORITHM_ECDSA);
    try {//from   www . ja  v a 2  s .c o  m
        KeyTools.testKey(keys1.getPrivate(), keys.getPublic(), "BC");
        assertTrue(false);
    } catch (InvalidKeyException e) {
        assertEquals("Not possible to sign and then verify with key pair.", e.getMessage());
    }

    // This will not do anything for a key which is not an org.ejbca.cvc.PublicKeyEC
    PublicKey pk = KeyTools.getECPublicKeyWithParams(keys.getPublic(), "prime192v1");
    assertTrue(pk.equals(keys.getPublic()));
    pk = KeyTools.getECPublicKeyWithParams(keys.getPublic(), pk);
    assertTrue(pk.equals(keys.getPublic()));

    AlgorithmParameterSpec spec = KeyTools.getKeyGenSpec(keys.getPublic());
    assertNotNull(spec);
    assertTrue((spec instanceof ECParameterSpec));

    assertTrue(KeyTools.isPrivateKeyExtractable(keys.getPrivate()));

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    PrintStream ps = new PrintStream(out);
    KeyTools.printPublicKeyInfo(keys.getPublic(), ps);
    ps.close();
    String str = out.toString();
    assertTrue(str.contains("Elliptic curve key"));
}

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

License:Open Source License

private PemObject createPemObject(Object o) throws IOException {
    String type;/*from   w  ww. ja  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.
 *///w  w 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.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;//from   ww  w. j a  va 2  s.co m
    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

public static void writeDSAPrivateKey(Writer _out, DSAPrivateKey obj, CipherSpec cipher, char[] passwd)
        throws IOException {
    BufferedWriter out = makeBuffered(_out);
    PrivateKeyInfo info = new PrivateKeyInfo((ASN1Sequence) new ASN1InputStream(getEncoded(obj)).readObject());
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    ASN1OutputStream aOut = new ASN1OutputStream(bOut);

    DSAParameter p = DSAParameter.getInstance(info.getPrivateKeyAlgorithm().getParameters());
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(new ASN1Integer(0));
    v.add(new ASN1Integer(p.getP()));
    v.add(new ASN1Integer(p.getQ()));
    v.add(new ASN1Integer(p.getG()));

    BigInteger x = obj.getX();//from  w ww  .  j a  v  a 2  s. c om
    BigInteger y = p.getG().modPow(x, p.getP());

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

    aOut.writeObject(new DLSequence(v));
    byte[] encoding = bOut.toByteArray();

    if (cipher != null && passwd != null) {
        writePemEncrypted(out, PEM_STRING_DSA, encoding, cipher, passwd);
    } else {
        writePemPlain(out, PEM_STRING_DSA, encoding);
    }
}

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 {/*from ww  w .  j ava2s.co 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);

}