Search in sources :

Example 6 with PrivateKeyInfo

use of org.bouncycastle.asn1.pkcs.PrivateKeyInfo in project XobotOS by xamarin.

the class MiscPEMGenerator method createPemObject.

private PemObject createPemObject(Object o) throws IOException {
    String type;
    byte[] encoding;
    if (o instanceof PemObject) {
        return (PemObject) o;
    }
    if (o instanceof PemObjectGenerator) {
        return ((PemObjectGenerator) o).generate();
    }
    if (o instanceof X509Certificate) {
        type = "CERTIFICATE";
        try {
            encoding = ((X509Certificate) o).getEncoded();
        } catch (CertificateEncodingException e) {
            throw new PemGenerationException("Cannot encode object: " + e.toString());
        }
    } else if (o instanceof X509CRL) {
        type = "X509 CRL";
        try {
            encoding = ((X509CRL) o).getEncoded();
        } catch (CRLException e) {
            throw new PemGenerationException("Cannot encode object: " + e.toString());
        }
    } else if (o instanceof KeyPair) {
        return createPemObject(((KeyPair) o).getPrivate());
    } else if (o instanceof PrivateKey) {
        PrivateKeyInfo info = new PrivateKeyInfo((ASN1Sequence) ASN1Object.fromByteArray(((Key) o).getEncoded()));
        if (o instanceof RSAPrivateKey) {
            type = "RSA PRIVATE KEY";
            encoding = info.getPrivateKey().getEncoded();
        } else if (o instanceof DSAPrivateKey) {
            type = "DSA PRIVATE KEY";
            DSAParameter p = DSAParameter.getInstance(info.getAlgorithmId().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 = ((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 (((PrivateKey) o).getAlgorithm().equals("ECDSA")) {
            type = "EC PRIVATE KEY";
            encoding = info.getPrivateKey().getEncoded();
        } else {
            throw new IOException("Cannot identify private key");
        }
    } else if (o instanceof PublicKey) {
        type = "PUBLIC KEY";
        encoding = ((PublicKey) o).getEncoded();
    } else if (o instanceof X509AttributeCertificate) {
        type = "ATTRIBUTE CERTIFICATE";
        encoding = ((X509V2AttributeCertificate) 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();
    } else {
        throw new PemGenerationException("unknown object passed - can't encode.");
    }
    return new PemObject(type, encoding);
}
Also used : X509CRL(java.security.cert.X509CRL) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PrivateKey(java.security.PrivateKey) X509AttributeCertificate(org.bouncycastle.x509.X509AttributeCertificate) DERInteger(org.bouncycastle.asn1.DERInteger) PemObjectGenerator(org.bouncycastle.util.io.pem.PemObjectGenerator) DERSequence(org.bouncycastle.asn1.DERSequence) ContentInfo(org.bouncycastle.asn1.cms.ContentInfo) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) DSAParameter(org.bouncycastle.asn1.x509.DSAParameter) CRLException(java.security.cert.CRLException) PKCS10CertificationRequest(org.bouncycastle.jce.PKCS10CertificationRequest) KeyPair(java.security.KeyPair) PemGenerationException(org.bouncycastle.util.io.pem.PemGenerationException) PublicKey(java.security.PublicKey) CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException) X509V2AttributeCertificate(org.bouncycastle.x509.X509V2AttributeCertificate) X509Certificate(java.security.cert.X509Certificate) PemObject(org.bouncycastle.util.io.pem.PemObject) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) BigInteger(java.math.BigInteger) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PublicKey(java.security.PublicKey) Key(java.security.Key) PrivateKey(java.security.PrivateKey) RSAPrivateCrtKey(java.security.interfaces.RSAPrivateCrtKey)

Example 7 with PrivateKeyInfo

use of org.bouncycastle.asn1.pkcs.PrivateKeyInfo in project XobotOS by xamarin.

the class MiscPEMGenerator method createPemObject.

private PemObject createPemObject(Object obj, String algorithm, char[] password, SecureRandom random) throws IOException {
    if (obj instanceof KeyPair) {
        return createPemObject(((KeyPair) obj).getPrivate(), algorithm, password, random);
    }
    String type = null;
    byte[] keyData = null;
    if (obj instanceof RSAPrivateCrtKey) {
        type = "RSA PRIVATE KEY";
        RSAPrivateCrtKey k = (RSAPrivateCrtKey) obj;
        RSAPrivateKeyStructure keyStruct = new RSAPrivateKeyStructure(k.getModulus(), k.getPublicExponent(), k.getPrivateExponent(), k.getPrimeP(), k.getPrimeQ(), k.getPrimeExponentP(), k.getPrimeExponentQ(), k.getCrtCoefficient());
        // convert to bytearray
        keyData = keyStruct.getEncoded();
    } else if (obj instanceof DSAPrivateKey) {
        type = "DSA PRIVATE KEY";
        DSAPrivateKey k = (DSAPrivateKey) obj;
        DSAParams p = k.getParams();
        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 = k.getX();
        BigInteger y = p.getG().modPow(x, p.getP());
        v.add(new DERInteger(y));
        v.add(new DERInteger(x));
        keyData = new DERSequence(v).getEncoded();
    } else if (obj instanceof PrivateKey && "ECDSA".equals(((PrivateKey) obj).getAlgorithm())) {
        type = "EC PRIVATE KEY";
        PrivateKeyInfo privInfo = PrivateKeyInfo.getInstance(ASN1Object.fromByteArray(((PrivateKey) obj).getEncoded()));
        keyData = privInfo.getPrivateKey().getEncoded();
    }
    if (type == null || keyData == null) {
        // TODO Support other types?
        throw new IllegalArgumentException("Object type not supported: " + obj.getClass().getName());
    }
    String dekAlgName = Strings.toUpperCase(algorithm);
    // Note: For backward compatibility
    if (dekAlgName.equals("DESEDE")) {
        dekAlgName = "DES-EDE3-CBC";
    }
    int ivLength = dekAlgName.startsWith("AES-") ? 16 : 8;
    byte[] iv = new byte[ivLength];
    random.nextBytes(iv);
    byte[] encData = PEMUtilities.crypt(true, provider, keyData, password, dekAlgName, iv);
    List headers = new ArrayList(2);
    headers.add(new PemHeader("Proc-Type", "4,ENCRYPTED"));
    headers.add(new PemHeader("DEK-Info", dekAlgName + "," + getHexEncoded(iv)));
    return new PemObject(type, headers, encData);
}
Also used : KeyPair(java.security.KeyPair) RSAPrivateCrtKey(java.security.interfaces.RSAPrivateCrtKey) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PrivateKey(java.security.PrivateKey) ArrayList(java.util.ArrayList) DSAParams(java.security.interfaces.DSAParams) DERInteger(org.bouncycastle.asn1.DERInteger) PemObject(org.bouncycastle.util.io.pem.PemObject) DERSequence(org.bouncycastle.asn1.DERSequence) RSAPrivateKeyStructure(org.bouncycastle.asn1.pkcs.RSAPrivateKeyStructure) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) BigInteger(java.math.BigInteger) ArrayList(java.util.ArrayList) List(java.util.List) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) PemHeader(org.bouncycastle.util.io.pem.PemHeader)

Example 8 with PrivateKeyInfo

use of org.bouncycastle.asn1.pkcs.PrivateKeyInfo in project XobotOS by xamarin.

the class PrivateKeyFactory method createKey.

/**
     * Create a private key parameter from the passed in PKCS8 PrivateKeyInfo object.
     * 
     * @param keyInfo the PrivateKeyInfo object containing the key material
     * @return a suitable private key parameter
     * @throws IOException on an error decoding the key
     */
public static AsymmetricKeyParameter createKey(PrivateKeyInfo keyInfo) throws IOException {
    AlgorithmIdentifier algId = keyInfo.getAlgorithmId();
    if (algId.getAlgorithm().equals(PKCSObjectIdentifiers.rsaEncryption)) {
        RSAPrivateKeyStructure keyStructure = new RSAPrivateKeyStructure((ASN1Sequence) keyInfo.getPrivateKey());
        return new RSAPrivateCrtKeyParameters(keyStructure.getModulus(), keyStructure.getPublicExponent(), keyStructure.getPrivateExponent(), keyStructure.getPrime1(), keyStructure.getPrime2(), keyStructure.getExponent1(), keyStructure.getExponent2(), keyStructure.getCoefficient());
    } else //      else if (algId.getObjectId().equals(X9ObjectIdentifiers.dhpublicnumber))
    if (algId.getObjectId().equals(PKCSObjectIdentifiers.dhKeyAgreement)) {
        DHParameter params = new DHParameter((ASN1Sequence) keyInfo.getAlgorithmId().getParameters());
        DERInteger derX = (DERInteger) keyInfo.getPrivateKey();
        BigInteger lVal = params.getL();
        int l = lVal == null ? 0 : lVal.intValue();
        DHParameters dhParams = new DHParameters(params.getP(), params.getG(), null, l);
        return new DHPrivateKeyParameters(derX.getValue(), dhParams);
    } else // END android-removed
    if (algId.getObjectId().equals(X9ObjectIdentifiers.id_dsa)) {
        DERInteger derX = (DERInteger) keyInfo.getPrivateKey();
        DEREncodable de = keyInfo.getAlgorithmId().getParameters();
        DSAParameters parameters = null;
        if (de != null) {
            DSAParameter params = DSAParameter.getInstance(de.getDERObject());
            parameters = new DSAParameters(params.getP(), params.getQ(), params.getG());
        }
        return new DSAPrivateKeyParameters(derX.getValue(), parameters);
    } else if (algId.getObjectId().equals(X9ObjectIdentifiers.id_ecPublicKey)) {
        X962Parameters params = new X962Parameters((DERObject) keyInfo.getAlgorithmId().getParameters());
        ECDomainParameters dParams = null;
        if (params.isNamedCurve()) {
            DERObjectIdentifier oid = (DERObjectIdentifier) params.getParameters();
            X9ECParameters ecP = X962NamedCurves.getByOID(oid);
            if (ecP == null) {
                ecP = SECNamedCurves.getByOID(oid);
                if (ecP == null) {
                    ecP = NISTNamedCurves.getByOID(oid);
                // BEGIN android-removed
                // if (ecP == null)
                // {
                //     ecP = TeleTrusTNamedCurves.getByOID(oid);
                // }
                // END android-removed
                }
            }
            dParams = new ECDomainParameters(ecP.getCurve(), ecP.getG(), ecP.getN(), ecP.getH(), ecP.getSeed());
        } else {
            X9ECParameters ecP = new X9ECParameters((ASN1Sequence) params.getParameters());
            dParams = new ECDomainParameters(ecP.getCurve(), ecP.getG(), ecP.getN(), ecP.getH(), ecP.getSeed());
        }
        ECPrivateKeyStructure ec = new ECPrivateKeyStructure((ASN1Sequence) keyInfo.getPrivateKey());
        return new ECPrivateKeyParameters(ec.getKey(), dParams);
    } else {
        throw new RuntimeException("algorithm identifier in key not recognised");
    }
}
Also used : ECDomainParameters(org.bouncycastle.crypto.params.ECDomainParameters) DHParameters(org.bouncycastle.crypto.params.DHParameters) DHPrivateKeyParameters(org.bouncycastle.crypto.params.DHPrivateKeyParameters) X9ECParameters(org.bouncycastle.asn1.x9.X9ECParameters) ECPrivateKeyStructure(org.bouncycastle.asn1.sec.ECPrivateKeyStructure) DERObjectIdentifier(org.bouncycastle.asn1.DERObjectIdentifier) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) DERInteger(org.bouncycastle.asn1.DERInteger) X962Parameters(org.bouncycastle.asn1.x9.X962Parameters) ECPrivateKeyParameters(org.bouncycastle.crypto.params.ECPrivateKeyParameters) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) DERObject(org.bouncycastle.asn1.DERObject) RSAPrivateKeyStructure(org.bouncycastle.asn1.pkcs.RSAPrivateKeyStructure) DEREncodable(org.bouncycastle.asn1.DEREncodable) DSAPrivateKeyParameters(org.bouncycastle.crypto.params.DSAPrivateKeyParameters) BigInteger(java.math.BigInteger) DSAParameter(org.bouncycastle.asn1.x509.DSAParameter) DHParameter(org.bouncycastle.asn1.pkcs.DHParameter) DSAParameters(org.bouncycastle.crypto.params.DSAParameters) RSAPrivateCrtKeyParameters(org.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters)

Example 9 with PrivateKeyInfo

use of org.bouncycastle.asn1.pkcs.PrivateKeyInfo in project Openfire by igniterealtime.

the class CertificateManager method parsePrivateKey.

/**
     * Parses a PrivateKey instance from a PEM representation.
     *
     * When the provided key is encrypted, the provided pass phrase is applied.
     *
     * @param pemRepresentation a PEM representation of a private key (cannot be null or empty)
     * @param passPhrase optional pass phrase (must be present if the private key is encrypted).
     * @return a PrivateKey instance (never null)
     */
public static PrivateKey parsePrivateKey(InputStream pemRepresentation, String passPhrase) throws IOException {
    if (passPhrase == null) {
        passPhrase = "";
    }
    try (//
    Reader reader = new InputStreamReader(pemRepresentation);
        PEMParser pemParser = new PEMParser(reader)) {
        final Object object = pemParser.readObject();
        final JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
        final KeyPair kp;
        if (object instanceof PEMEncryptedKeyPair) {
            // Encrypted key - we will use provided password
            final PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(passPhrase.toCharArray());
            kp = converter.getKeyPair(((PEMEncryptedKeyPair) object).decryptKeyPair(decProv));
        } else if (object instanceof PKCS8EncryptedPrivateKeyInfo) {
            // Encrypted key - we will use provided password
            try {
                final PKCS8EncryptedPrivateKeyInfo encryptedInfo = (PKCS8EncryptedPrivateKeyInfo) object;
                final InputDecryptorProvider provider = new JceOpenSSLPKCS8DecryptorProviderBuilder().build(passPhrase.toCharArray());
                final PrivateKeyInfo privateKeyInfo = encryptedInfo.decryptPrivateKeyInfo(provider);
                return converter.getPrivateKey(privateKeyInfo);
            } catch (PKCSException | OperatorCreationException e) {
                throw new IOException("Unable to decrypt private key.", e);
            }
        } else if (object instanceof PrivateKeyInfo) {
            return converter.getPrivateKey((PrivateKeyInfo) object);
        } else {
            // Unencrypted key - no password needed
            kp = converter.getKeyPair((PEMKeyPair) object);
        }
        return kp.getPrivate();
    }
}
Also used : KeyPair(java.security.KeyPair) PEMEncryptedKeyPair(org.bouncycastle.openssl.PEMEncryptedKeyPair) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) InputStreamReader(java.io.InputStreamReader) PEMDecryptorProvider(org.bouncycastle.openssl.PEMDecryptorProvider) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) JcePEMDecryptorProviderBuilder(org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo) IOException(java.io.IOException) PEMEncryptedKeyPair(org.bouncycastle.openssl.PEMEncryptedKeyPair) PEMParser(org.bouncycastle.openssl.PEMParser) InputDecryptorProvider(org.bouncycastle.operator.InputDecryptorProvider) JceOpenSSLPKCS8DecryptorProviderBuilder(org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo)

Example 10 with PrivateKeyInfo

use of org.bouncycastle.asn1.pkcs.PrivateKeyInfo in project robovm by robovm.

the class PrivateKeyInfo method toASN1Primitive.

/**
     * write out an RSA private key with its associated information
     * as described in PKCS8.
     * <pre>
     *      PrivateKeyInfo ::= SEQUENCE {
     *                              version Version,
     *                              privateKeyAlgorithm AlgorithmIdentifier {{PrivateKeyAlgorithms}},
     *                              privateKey PrivateKey,
     *                              attributes [0] IMPLICIT Attributes OPTIONAL 
     *                          }
     *      Version ::= INTEGER {v1(0)} (v1,...)
     *
     *      PrivateKey ::= OCTET STRING
     *
     *      Attributes ::= SET OF Attribute
     * </pre>
     */
public ASN1Primitive toASN1Primitive() {
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(new ASN1Integer(0));
    v.add(algId);
    v.add(privKey);
    if (attributes != null) {
        v.add(new DERTaggedObject(false, 0, attributes));
    }
    return new DERSequence(v);
}
Also used : DERSequence(org.bouncycastle.asn1.DERSequence) DERTaggedObject(org.bouncycastle.asn1.DERTaggedObject) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) ASN1Integer(org.bouncycastle.asn1.ASN1Integer)

Aggregations

PrivateKeyInfo (org.bouncycastle.asn1.pkcs.PrivateKeyInfo)8 X962Parameters (org.bouncycastle.asn1.x9.X962Parameters)8 X9ECParameters (org.bouncycastle.asn1.x9.X9ECParameters)8 DERInteger (org.bouncycastle.asn1.DERInteger)7 ECNamedCurveSpec (org.bouncycastle.jce.spec.ECNamedCurveSpec)6 IOException (java.io.IOException)5 DERObjectIdentifier (org.bouncycastle.asn1.DERObjectIdentifier)5 ECPrivateKeyStructure (org.bouncycastle.asn1.sec.ECPrivateKeyStructure)5 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)5 BigInteger (java.math.BigInteger)4 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)4 DERSequence (org.bouncycastle.asn1.DERSequence)4 KeyPair (java.security.KeyPair)3 PrivateKey (java.security.PrivateKey)3 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)3 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)3 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)3 DSAParameter (org.bouncycastle.asn1.x509.DSAParameter)3 DSAPrivateKey (java.security.interfaces.DSAPrivateKey)2 RSAPrivateCrtKey (java.security.interfaces.RSAPrivateCrtKey)2