Search in sources :

Example 46 with PrivateKeyInfo

use of com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo in project LinLong-Java by zhenwei1108.

the class JcaPKIXIdentityBuilder method build.

/**
 * Build an identity from the passed in key and certificate stream in PEM format.
 *
 * @param keyStream         the PEM stream containing the key
 * @param certificateStream the PEM stream containing the certificate
 * @return an identity object.
 * @throws IOException          on a general parsing error.
 * @throws CertificateException on a certificate parsing error.
 */
public JcaPKIXIdentity build(InputStream keyStream, InputStream certificateStream) throws IOException, CertificateException {
    PEMParser keyParser = new PEMParser(new InputStreamReader(keyStream));
    PrivateKey privKey;
    Object keyObj = keyParser.readObject();
    if (keyObj instanceof PEMKeyPair) {
        PEMKeyPair kp = (PEMKeyPair) keyObj;
        privKey = keyConverter.getPrivateKey(kp.getPrivateKeyInfo());
    } else if (keyObj instanceof PrivateKeyInfo) {
        privKey = keyConverter.getPrivateKey((PrivateKeyInfo) keyObj);
    } else {
        // TODO: handle encrypted private keys
        throw new IOException("unrecognised private key file");
    }
    PEMParser certParser = new PEMParser(new InputStreamReader(certificateStream));
    List certs = new ArrayList();
    Object certObj;
    while ((certObj = certParser.readObject()) != null) {
        certs.add(certConverter.getCertificate((X509CertificateHolder) certObj));
    }
    return new JcaPKIXIdentity(privKey, (X509Certificate[]) certs.toArray(new X509Certificate[certs.size()]));
}
Also used : PrivateKey(java.security.PrivateKey) PEMParser(com.github.zhenwei.pkix.openssl.PEMParser) InputStreamReader(java.io.InputStreamReader) JcaPKIXIdentity(com.github.zhenwei.pkix.jcajce.JcaPKIXIdentity) X509CertificateHolder(com.github.zhenwei.pkix.cert.X509CertificateHolder) ArrayList(java.util.ArrayList) PEMKeyPair(com.github.zhenwei.pkix.openssl.PEMKeyPair) ArrayList(java.util.ArrayList) List(java.util.List) IOException(java.io.IOException) PrivateKeyInfo(com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo) X509Certificate(java.security.cert.X509Certificate)

Example 47 with PrivateKeyInfo

use of com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo in project LinLong-Java by zhenwei1108.

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 X509TrustedCertificateBlock) {
        type = "TRUSTED CERTIFICATE";
        encoding = ((X509TrustedCertificateBlock) 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(0));
            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 {
            type = "PRIVATE KEY";
            encoding = info.getEncoded();
        }
    } 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 com.github.zhenwei.pkix.pkcs.PKCS10CertificationRequest) {
        type = "CERTIFICATE REQUEST";
        encoding = ((PKCS10CertificationRequest) o).getEncoded();
    } else if (o instanceof PKCS8EncryptedPrivateKeyInfo) {
        type = "ENCRYPTED PRIVATE KEY";
        encoding = ((PKCS8EncryptedPrivateKeyInfo) o).getEncoded();
    } else if (o instanceof ContentInfo) {
        type = "PKCS7";
        encoding = ((ContentInfo) o).getEncoded();
    } else {
        throw new PemGenerationException("unknown object passed - can't encode.");
    }
    if (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 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);
    }
    return new PemObject(type, encoding);
}
Also used : ArrayList(java.util.ArrayList) SubjectPublicKeyInfo(com.github.zhenwei.core.asn1.x509.SubjectPublicKeyInfo) PemObjectGenerator(com.github.zhenwei.core.util.io.pem.PemObjectGenerator) DERSequence(com.github.zhenwei.core.asn1.DERSequence) ContentInfo(com.github.zhenwei.pkix.util.asn1.cms.ContentInfo) ASN1EncodableVector(com.github.zhenwei.core.asn1.ASN1EncodableVector) ArrayList(java.util.ArrayList) List(java.util.List) DSAParameter(com.github.zhenwei.core.asn1.x509.DSAParameter) PKCS10CertificationRequest(com.github.zhenwei.pkix.pkcs.PKCS10CertificationRequest) PemGenerationException(com.github.zhenwei.core.util.io.pem.PemGenerationException) X509AttributeCertificateHolder(com.github.zhenwei.pkix.cert.X509AttributeCertificateHolder) ASN1Integer(com.github.zhenwei.core.asn1.ASN1Integer) PKCS8EncryptedPrivateKeyInfo(com.github.zhenwei.pkix.pkcs.PKCS8EncryptedPrivateKeyInfo) PemObject(com.github.zhenwei.core.util.io.pem.PemObject) X509CertificateHolder(com.github.zhenwei.pkix.cert.X509CertificateHolder) X509CRLHolder(com.github.zhenwei.pkix.cert.X509CRLHolder) BigInteger(java.math.BigInteger) PKCS8EncryptedPrivateKeyInfo(com.github.zhenwei.pkix.pkcs.PKCS8EncryptedPrivateKeyInfo) PrivateKeyInfo(com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo) ASN1ObjectIdentifier(com.github.zhenwei.core.asn1.ASN1ObjectIdentifier) PemHeader(com.github.zhenwei.core.util.io.pem.PemHeader)

Example 48 with PrivateKeyInfo

use of com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo in project LinLong-Java by zhenwei1108.

the class EncKeyWithID method toASN1Primitive.

/**
 * <pre>
 * EncKeyWithID ::= SEQUENCE {
 *      privateKey           PrivateKeyInfo,
 *      identifier CHOICE {
 *         string               UTF8String,
 *         generalName          GeneralName
 *     } OPTIONAL
 * }
 * </pre>
 *
 * @return an ASN.1 primitive composition of this EncKeyWithID.
 */
public ASN1Primitive toASN1Primitive() {
    ASN1EncodableVector v = new ASN1EncodableVector(2);
    v.add(privKeyInfo);
    if (identifier != null) {
        v.add(identifier);
    }
    return new DERSequence(v);
}
Also used : DERSequence(com.github.zhenwei.core.asn1.DERSequence) ASN1EncodableVector(com.github.zhenwei.core.asn1.ASN1EncodableVector)

Example 49 with PrivateKeyInfo

use of com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo in project LinLong-Java by zhenwei1108.

the class BcFKSKeyStoreSpi method engineGetKey.

public Key engineGetKey(String alias, char[] password) throws NoSuchAlgorithmException, UnrecoverableKeyException {
    ObjectData ent = (ObjectData) entries.get(alias);
    if (ent != null) {
        if (ent.getType().equals(PRIVATE_KEY) || ent.getType().equals(PROTECTED_PRIVATE_KEY)) {
            PrivateKey cachedKey = (PrivateKey) privateKeyCache.get(alias);
            if (cachedKey != null) {
                return cachedKey;
            }
            EncryptedPrivateKeyData encPrivData = EncryptedPrivateKeyData.getInstance(ent.getData());
            EncryptedPrivateKeyInfo encInfo = EncryptedPrivateKeyInfo.getInstance(encPrivData.getEncryptedPrivateKeyInfo());
            try {
                PrivateKeyInfo pInfo = PrivateKeyInfo.getInstance(decryptData("PRIVATE_KEY_ENCRYPTION", encInfo.getEncryptionAlgorithm(), password, encInfo.getEncryptedData()));
                KeyFactory kFact = helper.createKeyFactory(getPublicKeyAlg(pInfo.getPrivateKeyAlgorithm().getAlgorithm()));
                PrivateKey privateKey = kFact.generatePrivate(new PKCS8EncodedKeySpec(pInfo.getEncoded()));
                // check that the key pair and the certificate public key are consistent
                // TODO: new ConsistentKeyPair(engineGetCertificate(alias).getPublicKey(), privateKey);
                privateKeyCache.put(alias, privateKey);
                return privateKey;
            } catch (Exception e) {
                throw new UnrecoverableKeyException("BCFKS KeyStore unable to recover private key (" + alias + "): " + e.getMessage());
            }
        } else if (ent.getType().equals(SECRET_KEY) || ent.getType().equals(PROTECTED_SECRET_KEY)) {
            EncryptedSecretKeyData encKeyData = EncryptedSecretKeyData.getInstance(ent.getData());
            try {
                SecretKeyData keyData = SecretKeyData.getInstance(decryptData("SECRET_KEY_ENCRYPTION", encKeyData.getKeyEncryptionAlgorithm(), password, encKeyData.getEncryptedKeyData()));
                SecretKeyFactory kFact = helper.createSecretKeyFactory(keyData.getKeyAlgorithm().getId());
                return kFact.generateSecret(new SecretKeySpec(keyData.getKeyBytes(), keyData.getKeyAlgorithm().getId()));
            } catch (Exception e) {
                throw new UnrecoverableKeyException("BCFKS KeyStore unable to recover secret key (" + alias + "): " + e.getMessage());
            }
        } else {
            throw new UnrecoverableKeyException("BCFKS KeyStore unable to recover secret key (" + alias + "): type not recognized");
        }
    }
    return null;
}
Also used : PrivateKey(java.security.PrivateKey) ObjectData(com.github.zhenwei.core.asn1.bc.ObjectData) SecretKeyData(com.github.zhenwei.core.asn1.bc.SecretKeyData) EncryptedSecretKeyData(com.github.zhenwei.core.asn1.bc.EncryptedSecretKeyData) KeyStoreException(java.security.KeyStoreException) GeneralSecurityException(java.security.GeneralSecurityException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException) ParseException(java.text.ParseException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) CertificateException(java.security.cert.CertificateException) BadPaddingException(javax.crypto.BadPaddingException) NoSuchProviderException(java.security.NoSuchProviderException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) EncryptedSecretKeyData(com.github.zhenwei.core.asn1.bc.EncryptedSecretKeyData) SecretKeySpec(javax.crypto.spec.SecretKeySpec) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) EncryptedPrivateKeyInfo(com.github.zhenwei.core.asn1.pkcs.EncryptedPrivateKeyInfo) SecretKeyFactory(javax.crypto.SecretKeyFactory) EncryptedPrivateKeyData(com.github.zhenwei.core.asn1.bc.EncryptedPrivateKeyData) EncryptedPrivateKeyInfo(com.github.zhenwei.core.asn1.pkcs.EncryptedPrivateKeyInfo) PrivateKeyInfo(com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo) SecretKeyFactory(javax.crypto.SecretKeyFactory) KeyFactory(java.security.KeyFactory)

Example 50 with PrivateKeyInfo

use of com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo in project LinLong-Java by zhenwei1108.

the class McElieceKeyFactorySpi method engineGeneratePrivate.

/**
 * Converts, if possible, a key specification into a {@link BCMcEliecePrivateKey}.
 *
 * @param keySpec the key specification
 * @return the McEliece private key
 * @throws InvalidKeySpecException if the KeySpec is not supported.
 */
protected PrivateKey engineGeneratePrivate(KeySpec keySpec) throws InvalidKeySpecException {
    if (keySpec instanceof PKCS8EncodedKeySpec) {
        // get the DER-encoded Key according to PKCS#8 from the spec
        byte[] encKey = ((PKCS8EncodedKeySpec) keySpec).getEncoded();
        // decode the PKCS#8 data structure to the pki object
        PrivateKeyInfo pki;
        try {
            pki = PrivateKeyInfo.getInstance(ASN1Primitive.fromByteArray(encKey));
        } catch (IOException e) {
            throw new InvalidKeySpecException("Unable to decode PKCS8EncodedKeySpec: " + e);
        }
        try {
            if (PQCObjectIdentifiers.mcEliece.equals(pki.getPrivateKeyAlgorithm().getAlgorithm())) {
                McEliecePrivateKey key = McEliecePrivateKey.getInstance(pki.parsePrivateKey());
                return new BCMcEliecePrivateKey(new McEliecePrivateKeyParameters(key.getN(), key.getK(), key.getField(), key.getGoppaPoly(), key.getP1(), key.getP2(), key.getSInv()));
            } else {
                throw new InvalidKeySpecException("Unable to recognise OID in McEliece private key");
            }
        } catch (IOException cce) {
            throw new InvalidKeySpecException("Unable to decode PKCS8EncodedKeySpec.");
        }
    }
    throw new InvalidKeySpecException("Unsupported key specification: " + keySpec.getClass() + ".");
}
Also used : McEliecePrivateKeyParameters(com.github.zhenwei.core.pqc.crypto.mceliece.McEliecePrivateKeyParameters) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) IOException(java.io.IOException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) PrivateKeyInfo(com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo) McEliecePrivateKey(com.github.zhenwei.core.pqc.asn1.McEliecePrivateKey)

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