Search in sources :

Example 21 with PrivateKeyInfo

use of com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo in project jruby-openssl by jruby.

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 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();
    } else // 
    if (// 1.47 compatibility
    o instanceof java.security.cert.X509Certificate) {
        type = "CERTIFICATE";
        try {
            encoding = ((java.security.cert.X509Certificate) o).getEncoded();
        } catch (CertificateEncodingException e) {
            throw new PemGenerationException("Cannot encode object: " + e.toString());
        }
    } else if (// 1.47 compatibility
    o instanceof java.security.cert.X509CRL) {
        type = "X509 CRL";
        try {
            encoding = ((java.security.cert.X509CRL) o).getEncoded();
        } catch (CRLException e) {
            throw new PemGenerationException("Cannot encode object: " + e.toString());
        }
    } else if (// 1.47 compatibility
    o instanceof java.security.KeyPair) {
        return createPemObject(((java.security.KeyPair) o).getPrivate());
    } else if (// 1.47 compatibility
    o instanceof java.security.PrivateKey) {
        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 (// 1.47 compatibility
    o instanceof java.security.PublicKey) {
        type = "PUBLIC KEY";
        encoding = ((java.security.PublicKey) o).getEncoded();
    } else if (// 1.47 compatibility
    o instanceof X509AttributeCertificate) {
        type = "ATTRIBUTE CERTIFICATE";
        encoding = ((X509AttributeCertificate) o).getEncoded();
    } else // 
    // 
    // 
    {
        throw new PemGenerationException("unknown object passed - can't encode.");
    }
    if (// NEW STUFF (NOT IN OLD)
    encryptor != null) {
        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);
}
Also used : ArrayList(java.util.ArrayList) X509AttributeCertificate(org.bouncycastle.x509.X509AttributeCertificate) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) 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.pkcs.PKCS10CertificationRequest) PemGenerationException(org.bouncycastle.util.io.pem.PemGenerationException) X509AttributeCertificateHolder(org.bouncycastle.cert.X509AttributeCertificateHolder) CertificateEncodingException(java.security.cert.CertificateEncodingException) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) IOException(java.io.IOException) PemObject(org.bouncycastle.util.io.pem.PemObject) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) X509CRLHolder(org.bouncycastle.cert.X509CRLHolder) BigInteger(java.math.BigInteger) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) PemHeader(org.bouncycastle.util.io.pem.PemHeader)

Example 22 with PrivateKeyInfo

use of com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo in project xipki by xipki.

the class PrivateKeyCryptor method decrypt.

PrivateKey decrypt(PKCS8EncryptedPrivateKeyInfo encryptedPrivateKeyInfo) throws P11TokenException {
    ParamUtil.requireNonNull("encryptedPrivateKeyInfo", encryptedPrivateKeyInfo);
    PrivateKeyInfo privateKeyInfo;
    synchronized (decryptorProvider) {
        try {
            privateKeyInfo = encryptedPrivateKeyInfo.decryptPrivateKeyInfo(decryptorProvider);
        } catch (PKCSException ex) {
            throw new P11TokenException(ex.getMessage(), ex);
        }
    }
    AlgorithmIdentifier keyAlg = privateKeyInfo.getPrivateKeyAlgorithm();
    ASN1ObjectIdentifier keyAlgOid = keyAlg.getAlgorithm();
    String algoName;
    if (PKCSObjectIdentifiers.rsaEncryption.equals(keyAlgOid)) {
        algoName = "RSA";
    } else if (X9ObjectIdentifiers.id_dsa.equals(keyAlgOid)) {
        algoName = "DSA";
    } else if (X9ObjectIdentifiers.id_ecPublicKey.equals(keyAlgOid)) {
        algoName = "EC";
    } else {
        throw new P11TokenException("unknown private key algorithm " + keyAlgOid.getId());
    }
    try {
        KeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyInfo.getEncoded());
        KeyFactory keyFactory = KeyFactory.getInstance(algoName, "BC");
        return keyFactory.generatePrivate(keySpec);
    } catch (IOException | NoSuchAlgorithmException | NoSuchProviderException | InvalidKeySpecException ex) {
        throw new P11TokenException(ex.getClass().getName() + ": " + ex.getMessage(), ex);
    }
}
Also used : P11TokenException(org.xipki.security.exception.P11TokenException) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) KeySpec(java.security.spec.KeySpec) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) PKCSException(org.bouncycastle.pkcs.PKCSException) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) NoSuchProviderException(java.security.NoSuchProviderException) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) KeyFactory(java.security.KeyFactory)

Example 23 with PrivateKeyInfo

use of com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo in project xipki by xipki.

the class PrivateKeyCryptor method encrypt.

PKCS8EncryptedPrivateKeyInfo encrypt(PrivateKey privateKey) {
    ParamUtil.requireNonNull("privateKey", privateKey);
    PrivateKeyInfo privateKeyInfo = PrivateKeyInfo.getInstance(privateKey.getEncoded());
    PKCS8EncryptedPrivateKeyInfoBuilder builder = new PKCS8EncryptedPrivateKeyInfoBuilder(privateKeyInfo);
    synchronized (encryptor) {
        return builder.build(encryptor);
    }
}
Also used : PKCS8EncryptedPrivateKeyInfoBuilder(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfoBuilder) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo)

Example 24 with PrivateKeyInfo

use of com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo in project runwar by cfmlprojects.

the class SSLUtil method loadPemPrivateKey.

private static PrivateKey loadPemPrivateKey(final File file, final char[] passphrase) throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    final PEMParser pemParser = new PEMParser(new BufferedReader(new FileReader(file)));
    final PEMDecryptorProvider build = new JcePEMDecryptorProviderBuilder().build(passphrase);
    final JcaPEMKeyConverter jcaPEMKeyConverter = new JcaPEMKeyConverter();
    PrivateKey privateKey;
    try {
        final Object object = pemParser.readObject();
        if (object instanceof PEMEncryptedKeyPair) {
            privateKey = jcaPEMKeyConverter.getKeyPair(((PEMEncryptedKeyPair) object).decryptKeyPair(build)).getPrivate();
        } else {
            PrivateKeyInfo privateKeyInfo;
            if (object instanceof PEMKeyPair) {
                privateKeyInfo = ((PEMKeyPair) object).getPrivateKeyInfo();
            } else {
                privateKeyInfo = (PrivateKeyInfo) object;
            }
            if (privateKeyInfo != null) {
                privateKey = new JcaPEMKeyConverter().getPrivateKey(privateKeyInfo);
            } else {
                final KeyStore keyStore = KeyStore.getInstance("PKCS12", "BC");
                final FileInputStream fileInputStream = new FileInputStream(file);
                keyStore.load(fileInputStream, passphrase);
                fileInputStream.close();
                final Enumeration<String> aliases = keyStore.aliases();
                String alias = "";
                while (aliases.hasMoreElements()) {
                    alias = aliases.nextElement();
                }
                privateKey = (PrivateKey) keyStore.getKey(alias, passphrase);
            }
        }
    } finally {
        pemParser.close();
    }
    pemParser.close();
    return privateKey;
}
Also used : PrivateKey(java.security.PrivateKey) PEMDecryptorProvider(org.bouncycastle.openssl.PEMDecryptorProvider) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) JcePEMDecryptorProviderBuilder(org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder) KeyStore(java.security.KeyStore) FileInputStream(java.io.FileInputStream) PEMEncryptedKeyPair(org.bouncycastle.openssl.PEMEncryptedKeyPair) PEMParser(org.bouncycastle.openssl.PEMParser) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) EncryptedPrivateKeyInfo(javax.crypto.EncryptedPrivateKeyInfo) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 25 with PrivateKeyInfo

use of com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo in project keystore-explorer by kaikramer.

the class EccUtil method detectEdDSACurve.

/**
 * Detect which one of the two EdDSA curves (Ed25519 or Ed448) the given privateKey is.
 *
 * @param privateKey An EdDSA private key
 * @return Ed25519 or Ed448
 * @throws InvalidParameterException if privateKey is not a EdDSA key
 */
public static EdDSACurves detectEdDSACurve(PrivateKey privateKey) {
    PrivateKeyInfo privateKeyInfo = PrivateKeyInfo.getInstance(privateKey.getEncoded());
    AlgorithmIdentifier algorithm = privateKeyInfo.getPrivateKeyAlgorithm();
    ASN1ObjectIdentifier algOid = algorithm.getAlgorithm();
    return EdDSACurves.resolve(algOid);
}
Also used : PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier)

Aggregations

PrivateKeyInfo (org.bouncycastle.asn1.pkcs.PrivateKeyInfo)100 IOException (java.io.IOException)69 JcaPEMKeyConverter (org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter)53 PEMParser (org.bouncycastle.openssl.PEMParser)49 PrivateKey (java.security.PrivateKey)37 PEMKeyPair (org.bouncycastle.openssl.PEMKeyPair)35 PKCS8EncryptedPrivateKeyInfo (org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo)33 PrivateKeyInfo (com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo)25 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)25 InputDecryptorProvider (org.bouncycastle.operator.InputDecryptorProvider)25 JceOpenSSLPKCS8DecryptorProviderBuilder (org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder)20 AlgorithmIdentifier (com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier)18 BigInteger (java.math.BigInteger)17 ByteArrayInputStream (java.io.ByteArrayInputStream)16 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)16 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)16 KeyPair (java.security.KeyPair)15 PEMEncryptedKeyPair (org.bouncycastle.openssl.PEMEncryptedKeyPair)15 ASN1ObjectIdentifier (com.github.zhenwei.core.asn1.ASN1ObjectIdentifier)14 InputStreamReader (java.io.InputStreamReader)14