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

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

Introduction

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

Prototype

public static PrivateKeyInfo getInstance(Object obj) 

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 {//w  w  w  . j  a  v a 2s  .c  om
        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   www . j a  va  2  s  .  co 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:edu.vt.middleware.crypt.io.PrivateKeyCredentialReader.java

License:Open Source License

/** {@inheritDoc} */
protected PrivateKey decode(final byte[] encoded) throws CryptException {
    final KeySpec spec;
    final String algorithm;

    final ASN1Object o;
    try {/*from   www.  j a  v  a  2 s.co  m*/
        o = ASN1Object.fromByteArray(encoded);
    } catch (Exception e) {
        throw new CryptException("Key is not ASN.1 encoded data.");
    }

    // Assume PKCS#8 and try OpenSSL "traditional" format as backup
    PrivateKeyInfo pi;
    try {
        pi = PrivateKeyInfo.getInstance(o);
    } catch (Exception e) {
        pi = null;
    }
    if (pi != null) {
        final String algOid = pi.getAlgorithmId().getObjectId().getId();
        if (RSA_ID.equals(pi.getAlgorithmId().getObjectId())) {
            algorithm = "RSA";
        } else if (EC_ID.equals(pi.getAlgorithmId().getObjectId())) {
            algorithm = "EC";
        } else if (DSA_ID.equals(pi.getAlgorithmId().getObjectId())) {
            algorithm = "DSA";
        } else {
            throw new CryptException("Unsupported PKCS#8 algorithm ID " + algOid);
        }
        try {
            spec = new PKCS8EncodedKeySpec(encoded);
        } catch (Exception e) {
            throw new CryptException("Invalid PKCS#8 private key format.", e);
        }
    } else if (o instanceof DERObjectIdentifier) {
        // Indicates we have an EC key in the default OpenSSL format emitted by
        //
        // openssl ecparam -name xxxx -genkey
        //
        // which is the concatenation of the named curve OID and a sequence of 1
        // containing the private point
        algorithm = "EC";

        final DERObjectIdentifier oid = (DERObjectIdentifier) o;
        final int len = encoded[1];
        final byte[] privatePart = new byte[encoded.length - len - 2];
        System.arraycopy(encoded, len + 2, privatePart, 0, privatePart.length);
        try {
            final ASN1Sequence seq = (ASN1Sequence) ASN1Sequence.fromByteArray(privatePart);
            spec = new ECPrivateKeySpec(DERInteger.getInstance(seq.getObjectAt(0)).getValue(),
                    ECUtils.fromNamedCurve(oid));
        } catch (IOException e) {
            throw new CryptException("Error reading elliptic curve key data.", e);
        }
    } else {
        // OpenSSL "traditional" format is an ASN.1 sequence of key parameters

        // Detect key type based on number and types of parameters:
        // RSA -> {version, mod, pubExp, privExp, prime1, prime2, exp1, exp2, c}
        // DSA -> {version, p, q, g, pubExp, privExp}
        // EC ->  {version, privateKey, parameters, publicKey}
        final DERSequence sequence = (DERSequence) o;
        if (sequence.size() == 9) {
            if (logger.isDebugEnabled()) {
                logger.debug("Reading OpenSSL format RSA private key.");
            }
            algorithm = "RSA";
            try {
                spec = new RSAPrivateCrtKeySpec(DERInteger.getInstance(sequence.getObjectAt(1)).getValue(),
                        DERInteger.getInstance(sequence.getObjectAt(2)).getValue(),
                        DERInteger.getInstance(sequence.getObjectAt(3)).getValue(),
                        DERInteger.getInstance(sequence.getObjectAt(4)).getValue(),
                        DERInteger.getInstance(sequence.getObjectAt(5)).getValue(),
                        DERInteger.getInstance(sequence.getObjectAt(6)).getValue(),
                        DERInteger.getInstance(sequence.getObjectAt(7)).getValue(),
                        DERInteger.getInstance(sequence.getObjectAt(8)).getValue());
            } catch (Exception e) {
                throw new CryptException("Invalid RSA key.", e);
            }
        } else if (sequence.size() == 6) {
            if (logger.isDebugEnabled()) {
                logger.debug("Reading OpenSSL format DSA private key.");
            }
            algorithm = "DSA";
            try {
                spec = new DSAPrivateKeySpec(DERInteger.getInstance(sequence.getObjectAt(5)).getValue(),
                        DERInteger.getInstance(sequence.getObjectAt(1)).getValue(),
                        DERInteger.getInstance(sequence.getObjectAt(2)).getValue(),
                        DERInteger.getInstance(sequence.getObjectAt(3)).getValue());
            } catch (Exception e) {
                throw new CryptException("Invalid DSA key.", e);
            }
        } else if (sequence.size() == 4) {
            if (logger.isDebugEnabled()) {
                logger.debug("Reading OpenSSL format EC private key.");
            }
            algorithm = "EC";
            spec = ECUtils.readEncodedPrivateKey(sequence);
        } else {
            throw new CryptException("Invalid OpenSSL traditional private key format.");
        }
    }
    try {
        return CryptProvider.getKeyFactory(algorithm).generatePrivate(spec);
    } catch (InvalidKeySpecException e) {
        throw new CryptException("Invalid key specification", e);
    }
}

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;/*from w  ww. j a  v  a2 s  .c o  m*/
    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);
    printB64(bout.toByteArray(), out);
    out.println("-----END RSA PRIVATE KEY-----");
}

From source file:io.aos.crypto.spl05.EncryptedPrivateKeyInfoExample.java

License:Apache License

public static void main(String[] args) throws Exception {
    // generate a key pair
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "BC");
    kpg.initialize(128, Utils.createFixedRandom());

    KeyPair pair = kpg.generateKeyPair();

    // wrapping step
    char[] password = "hello".toCharArray();
    byte[] salt = new byte[20];
    int iCount = 100;
    String pbeAlgorithm = "PBEWithSHAAnd3-KeyTripleDES-CBC";
    PBEKeySpec pbeKeySpec = new PBEKeySpec(password, salt, iCount);
    SecretKeyFactory secretKeyFact = SecretKeyFactory.getInstance(pbeAlgorithm, "BC");
    Cipher cipher = Cipher.getInstance(pbeAlgorithm, "BC");

    cipher.init(Cipher.WRAP_MODE, secretKeyFact.generateSecret(pbeKeySpec));

    byte[] wrappedKey = cipher.wrap(pair.getPrivate());

    System.out.println(//from   www  . ja v a 2  s. c o m
            ASN1Dump.dumpAsString(new ASN1InputStream(cipher.getParameters().getEncoded()).readObject()));

    // create carrier   
    EncryptedPrivateKeyInfo pInfo = new EncryptedPrivateKeyInfo(cipher.getParameters(), wrappedKey);

    // unwrapping step - note we only use the password
    pbeKeySpec = new PBEKeySpec(password);

    cipher = Cipher.getInstance(pInfo.getAlgName(), "BC");

    cipher.init(Cipher.DECRYPT_MODE, secretKeyFact.generateSecret(pbeKeySpec), pInfo.getAlgParameters());

    PKCS8EncodedKeySpec pkcs8Spec = pInfo.getKeySpec(cipher);
    KeyFactory keyFact = KeyFactory.getInstance("RSA", "BC");
    PrivateKey privKey = keyFact.generatePrivate(pkcs8Spec);

    ASN1InputStream aIn = new ASN1InputStream(pkcs8Spec.getEncoded());
    PrivateKeyInfo info = PrivateKeyInfo.getInstance(aIn.readObject());

    System.out.println(ASN1Dump.dumpAsString(info));
    System.out.println(ASN1Dump.dumpAsString(info.getPrivateKey()));

    if (privKey.equals(pair.getPrivate())) {
        System.out.println("key recovery successful");
    } else {
        System.out.println("key recovery failed");
    }
}

From source file:io.aos.crypto.spl05.PKCS8EncodedKeySpecExample.java

License:Apache License

public static void main(String[] args) throws Exception {
    // create the keys
    KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "BC");

    generator.initialize(128, Utils.createFixedRandom());

    KeyPair pair = generator.generateKeyPair();

    // dump private key
    ASN1InputStream aIn = new ASN1InputStream(pair.getPrivate().getEncoded());
    PrivateKeyInfo info = PrivateKeyInfo.getInstance(aIn.readObject());

    System.out.println(ASN1Dump.dumpAsString(info));
    System.out.println(ASN1Dump.dumpAsString(info.getPrivateKey()));

    // create from specification
    PKCS8EncodedKeySpec pkcs8Spec = new PKCS8EncodedKeySpec(pair.getPrivate().getEncoded());
    KeyFactory keyFact = KeyFactory.getInstance("RSA", "BC");
    PrivateKey privKey = keyFact.generatePrivate(pkcs8Spec);

    if (privKey.equals(pair.getPrivate())) {
        System.out.println("key recovery successful");
    } else {//from  w w  w. ja  v a2s . c  o m
        System.out.println("key recovery failed");
    }
}

From source file:net.jradius.client.auth.EAPTLSAuthenticator.java

License:Open Source License

/**
 * Create a private key parameter from a PKCS8 PrivateKeyInfo encoding.
 * //  www  .  j  a  va 2  s.  c o m
 * @param privateKeyInfoData the PrivateKeyInfo encoding
 * @return a suitable private key parameter
 * @throws IOException on an error decoding the key
 */
public static AsymmetricKeyParameter createKey(byte[] privateKeyInfoData) throws IOException {
    return createKey(PrivateKeyInfo.getInstance(ASN1Object.fromByteArray(privateKeyInfoData)));
}

From source file:net.jradius.client.auth.EAPTLSAuthenticator.java

License:Open Source License

/**
 * Create a private key parameter from a PKCS8 PrivateKeyInfo encoding read from a stream.
 * //  www . j  a v a 2  s .  co  m
 * @param inStr the stream to read the PrivateKeyInfo encoding from
 * @return a suitable private key parameter
 * @throws IOException on an error decoding the key
 */
public static AsymmetricKeyParameter createKey(InputStream inStr) throws IOException {
    return createKey(PrivateKeyInfo.getInstance(new ASN1InputStream(inStr).readObject()));
}

From source file:okhttp3.tls.HeldCertificate.java

License:Apache License

private ByteString pkcs1Bytes() {
    try {//from  w w  w. j  ava2 s. c o  m
        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.apache.kerby.pkix.EnvelopedDataEngine.java

License:Apache License

/**
 * Uses a private key to decrypt data in a CMS EnvelopedData structure and
 * returns the recovered (decrypted) data bytes.
 *
 * @param envelopedDataBytes/* ww w .  j  av  a2  s.  c o  m*/
 * @param privateKey
 * @return The recovered (decrypted) data bytes.
 * @throws IOException
 * @throws CMSException
 */
@SuppressWarnings("unchecked")
public static byte[] getUnenvelopedData(byte[] envelopedDataBytes, PrivateKey privateKey)
        throws CMSException, IOException {
    CMSEnvelopedData envelopedData = new CMSEnvelopedData(envelopedDataBytes);

    // Set up to iterate through the recipients.
    RecipientInformationStore recipients = envelopedData.getRecipientInfos();
    Collection c = recipients.getRecipients();
    Iterator it = c.iterator();

    byte[] recData = new byte[0];
    while (it.hasNext()) {
        RecipientInformation recipient = (RecipientInformation) it.next();

        recData = recipient.getContent(new BcRSAKeyTransEnvelopedRecipient(
                PrivateKeyFactory.createKey(PrivateKeyInfo.getInstance(privateKey.getEncoded()))));
    }
    return recData;
}