Example usage for org.bouncycastle.asn1.pkcs RSAPrivateKeyStructure toASN1Primitive

List of usage examples for org.bouncycastle.asn1.pkcs RSAPrivateKeyStructure toASN1Primitive

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.pkcs RSAPrivateKeyStructure toASN1Primitive.

Prototype

public ASN1Primitive toASN1Primitive() 

Source Link

Document

This outputs the key in PKCS1v2 format.

Usage

From source file:org.globus.gsi.bc.BouncyCastleOpenSSLKey.java

License:Apache License

protected byte[] getEncoded(PrivateKey key) {
    String format = key.getFormat();
    if (format != null && (format.equalsIgnoreCase("PKCS#8") || format.equalsIgnoreCase("PKCS8"))) {
        try {/*from   w w  w.  j  a v  a 2s. c o  m*/
            ASN1Primitive keyInfo = BouncyCastleUtil.toASN1Primitive(key.getEncoded());
            PrivateKeyInfo pkey = new PrivateKeyInfo((ASN1Sequence) keyInfo);
            ASN1Primitive derKey = pkey.getPrivateKey();
            return BouncyCastleUtil.toByteArray(derKey);
        } catch (IOException e) {
            // that should never happen
            logger.warn("This shouldn't have happened.", e);
            return new byte[] {};
        }
    } else if (format != null && format.equalsIgnoreCase("PKCS#1") && key instanceof RSAPrivateCrtKey) {
        // this condition will rarely be true
        RSAPrivateCrtKey pKey = (RSAPrivateCrtKey) key;
        RSAPrivateKeyStructure st = new RSAPrivateKeyStructure(pKey.getModulus(), pKey.getPublicExponent(),
                pKey.getPrivateExponent(), pKey.getPrimeP(), pKey.getPrimeQ(), pKey.getPrimeExponentP(),
                pKey.getPrimeExponentQ(), pKey.getCrtCoefficient());
        ASN1Primitive ob = st.toASN1Primitive();

        try {
            return BouncyCastleUtil.toByteArray(ob);
        } catch (IOException e) {
            // that should never happen
            return new byte[0];
        }
    } else {
        return new byte[0];
    }
}