Search in sources :

Example 71 with PrivateKeyInfo

use of com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo in project DataSpaceConnector by eclipse-dataspaceconnector.

the class DefaultPrivateKeyParseFunction method apply.

@Override
public PrivateKey apply(String encoded) {
    var pemParser = new PEMParser(new StringReader(encoded));
    var converter = new JcaPEMKeyConverter();
    try {
        var o = pemParser.readObject();
        if (o instanceof PEMKeyPair) {
            var keyPair = (PEMKeyPair) o;
            return converter.getKeyPair(keyPair).getPrivate();
        } else if (o instanceof PrivateKeyInfo) {
            var privateKeyInfo = PrivateKeyInfo.getInstance(o);
            return converter.getPrivateKey(privateKeyInfo);
        } else {
            throw new EdcException(Optional.ofNullable(o).map(obj -> "Invalid object type: " + obj.getClass()).orElse("Object cannot be null"));
        }
    } catch (IOException e) {
        throw new EdcException(e);
    }
}
Also used : JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) StringReader(java.io.StringReader) PrivateKey(java.security.PrivateKey) PEMParser(org.bouncycastle.openssl.PEMParser) Optional(java.util.Optional) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) EdcException(org.eclipse.dataspaceconnector.spi.EdcException) IOException(java.io.IOException) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) Function(java.util.function.Function) PEMParser(org.bouncycastle.openssl.PEMParser) StringReader(java.io.StringReader) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) EdcException(org.eclipse.dataspaceconnector.spi.EdcException) IOException(java.io.IOException) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo)

Example 72 with PrivateKeyInfo

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

the class CmpAgent method requestCertificate0.

// method requestCertificate
private EnrollCertResponse requestCertificate0(PKIMessage reqMessage, Map<BigInteger, String> reqIdIdMap, int expectedBodyType, ReqRespDebug debug) throws CmpClientException, PkiErrorException {
    VerifiedPkiMessage response = signAndSend(reqMessage, debug);
    checkProtection(response);
    PKIBody respBody = response.getPkiMessage().getBody();
    final int bodyType = respBody.getType();
    if (PKIBody.TYPE_ERROR == bodyType) {
        ErrorMsgContent content = ErrorMsgContent.getInstance(respBody.getContent());
        throw new PkiErrorException(content.getPKIStatusInfo());
    } else if (expectedBodyType != bodyType) {
        throw new CmpClientException(String.format("unknown PKI body type %s instead the expected [%s, %s]", bodyType, expectedBodyType, PKIBody.TYPE_ERROR));
    }
    CertRepMessage certRep = CertRepMessage.getInstance(respBody.getContent());
    CertResponse[] certResponses = certRep.getResponse();
    EnrollCertResponse result = new EnrollCertResponse();
    // CA certificates
    CMPCertificate[] caPubs = certRep.getCaPubs();
    if (caPubs != null && caPubs.length > 0) {
        for (CMPCertificate caPub : caPubs) {
            if (caPub != null) {
                result.addCaCertificate(caPub);
            }
        }
    }
    CertificateConfirmationContentBuilder certConfirmBuilder = null;
    if (!CmpUtil.isImplictConfirm(response.getPkiMessage().getHeader())) {
        certConfirmBuilder = new CertificateConfirmationContentBuilder();
    }
    boolean requireConfirm = false;
    // We only accept the certificates which are requested.
    for (CertResponse certResp : certResponses) {
        PKIStatusInfo statusInfo = certResp.getStatus();
        int status = statusInfo.getStatus().intValue();
        BigInteger certReqId = certResp.getCertReqId().getValue();
        String thisId = reqIdIdMap.get(certReqId);
        if (thisId != null) {
            reqIdIdMap.remove(certReqId);
        } else if (reqIdIdMap.size() == 1) {
            thisId = reqIdIdMap.values().iterator().next();
            reqIdIdMap.clear();
        }
        if (thisId == null) {
            // ignore it. this cert is not requested by me
            continue;
        }
        ResultEntry resultEntry;
        if (status == PKIStatus.GRANTED || status == PKIStatus.GRANTED_WITH_MODS) {
            CertifiedKeyPair cvk = certResp.getCertifiedKeyPair();
            if (cvk == null) {
                return null;
            }
            CMPCertificate cmpCert = cvk.getCertOrEncCert().getCertificate();
            if (cmpCert == null) {
                return null;
            }
            if (requestor == null) {
                result.addResultEntry(new ResultEntry.Error(thisId, PKISTATUS_RESPONSE_ERROR, PKIFailureInfo.systemFailure, "could not decrypt PrivateKeyInfo/requestor is null"));
                continue;
            }
            PrivateKeyInfo privKeyInfo = null;
            if (cvk.getPrivateKey() != null) {
                // decryp the encrypted private key
                byte[] decryptedValue;
                try {
                    if (requestor instanceof Requestor.SignatureCmpRequestor) {
                        ConcurrentContentSigner requestSigner = ((Requestor.SignatureCmpRequestor) requestor).getSigner();
                        if (!(requestSigner.getSigningKey() instanceof PrivateKey)) {
                            throw new XiSecurityException("no decryption key is configured");
                        }
                        decryptedValue = decrypt(cvk.getPrivateKey(), (PrivateKey) requestSigner.getSigningKey());
                    } else {
                        decryptedValue = decrypt(cvk.getPrivateKey(), ((Requestor.PbmMacCmpRequestor) requestor).getPassword());
                    }
                } catch (XiSecurityException ex) {
                    result.addResultEntry(new ResultEntry.Error(thisId, PKISTATUS_RESPONSE_ERROR, PKIFailureInfo.systemFailure, "could not decrypt PrivateKeyInfo"));
                    continue;
                }
                privKeyInfo = PrivateKeyInfo.getInstance(decryptedValue);
            }
            resultEntry = new ResultEntry.EnrollCert(thisId, cmpCert, privKeyInfo, status);
            if (certConfirmBuilder != null) {
                requireConfirm = true;
                X509CertificateHolder certHolder = new X509CertificateHolder(cmpCert.getX509v3PKCert());
                certConfirmBuilder.addAcceptedCertificate(certHolder, certReqId);
            }
        } else {
            PKIFreeText statusString = statusInfo.getStatusString();
            String errorMessage = (statusString == null) ? null : statusString.getStringAt(0).getString();
            int failureInfo = statusInfo.getFailInfo().intValue();
            resultEntry = new ResultEntry.Error(thisId, status, failureInfo, errorMessage);
        }
        result.addResultEntry(resultEntry);
    }
    if (CollectionUtil.isNotEmpty(reqIdIdMap)) {
        for (Entry<BigInteger, String> entry : reqIdIdMap.entrySet()) {
            result.addResultEntry(new ResultEntry.Error(entry.getValue(), PKISTATUS_NO_ANSWER));
        }
    }
    if (!requireConfirm) {
        return result;
    }
    PKIMessage confirmRequest = buildCertConfirmRequest(response.getPkiMessage().getHeader().getTransactionID(), certConfirmBuilder);
    response = signAndSend(confirmRequest, debug);
    checkProtection(response);
    return result;
}
Also used : PrivateKey(java.security.PrivateKey) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo)

Example 73 with PrivateKeyInfo

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

the class IaikP11Slot method generateECKeypairOtf0.

private PrivateKeyInfo generateECKeypairOtf0(long keyType, long mech, ASN1ObjectIdentifier curveId) throws P11TokenException {
    ECPrivateKey privateKeyTemplate = new ECPrivateKey(keyType);
    ECPublicKey publicKeyTemplate = new ECPublicKey(keyType);
    setPrivateKeyAttrsOtf(privateKeyTemplate);
    if (!GMObjectIdentifiers.sm2p256v1.equals(curveId)) {
        byte[] encodedCurveId;
        try {
            encodedCurveId = curveId.getEncoded();
        } catch (IOException ex) {
            throw new P11TokenException(ex.getMessage(), ex);
        }
        publicKeyTemplate.getEcdsaParams().setByteArrayValue(encodedCurveId);
    }
    ConcurrentBagEntry<Session> bagEntry = borrowSession();
    try {
        Session session = bagEntry.value();
        KeyPair keypair = null;
        try {
            keypair = session.generateKeyPair(Mechanism.get(mech), publicKeyTemplate, privateKeyTemplate);
            ECPrivateKey sk = (ECPrivateKey) keypair.getPrivateKey();
            ECPublicKey pk = (ECPublicKey) keypair.getPublicKey();
            if (KeyType.EC_EDWARDS == keyType || KeyType.EC_MONTGOMERY == keyType) {
                AlgorithmIdentifier algId = new AlgorithmIdentifier(curveId);
                byte[] encodedPublicPoint = ASN1OctetString.getInstance(pk.getEcPoint().getByteArrayValue()).getOctets();
                byte[] privValue = sk.getValue().getByteArrayValue();
                IoUtil.save("logs/ed25519-prikey.bin", privValue);
                PrivateKeyInfo pki = new PrivateKeyInfo(algId, new DEROctetString(privValue), null, encodedPublicPoint);
                IoUtil.save("logs/ed25519.der", pki.getEncoded());
                return pki;
            } else {
                AlgorithmIdentifier algId = new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, curveId);
                byte[] encodedPublicPoint = ASN1OctetString.getInstance(pk.getEcPoint().getByteArrayValue()).getOctets();
                if (encodedPublicPoint[0] != 4) {
                    throw new P11TokenException("EcPoint does not start with 0x04");
                }
                int orderBigLen = (encodedPublicPoint.length - 1) / 2 * 8;
                return new PrivateKeyInfo(algId, new org.bouncycastle.asn1.sec.ECPrivateKey(orderBigLen, new BigInteger(1, sk.getValue().getByteArrayValue()), new DERBitString(encodedPublicPoint), null));
            }
        } catch (TokenException | IOException ex) {
            throw new P11TokenException("could not generate keypair " + Functions.mechanismCodeToString(mech), ex);
        } finally {
            if (keypair != null) {
                destroyObject(session, keypair.getPrivateKey());
                destroyObject(session, keypair.getPublicKey());
            }
        }
    } finally {
        sessions.requite(bagEntry);
    }
}
Also used : IOException(java.io.IOException) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) BigInteger(java.math.BigInteger) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo)

Example 74 with PrivateKeyInfo

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

the class EmulatorP11Slot method generateDSAKeypairOtf0.

// method generateDSAKeypair0
@Override
protected PrivateKeyInfo generateDSAKeypairOtf0(BigInteger p, BigInteger q, BigInteger g) throws P11TokenException {
    DSAParameters spec = new DSAParameters(p, q, g);
    try {
        KeyPair kp = KeyUtil.generateDSAKeypair(spec, random);
        DSAParameter parameter = new DSAParameter(spec.getP(), spec.getQ(), spec.getG());
        AlgorithmIdentifier algId = new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa, parameter);
        byte[] publicKey = new ASN1Integer(((DSAPublicKey) kp.getPublic()).getY()).getEncoded();
        // DSA private keys are represented as BER-encoded ASN.1 type INTEGER.
        DSAPrivateKey priv = (DSAPrivateKey) kp.getPrivate();
        return new PrivateKeyInfo(algId, new ASN1Integer(priv.getX()), null, publicKey);
    } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidAlgorithmParameterException | IOException ex) {
        throw new P11TokenException(ex.getMessage(), ex);
    }
}
Also used : ASN1Integer(org.bouncycastle.asn1.ASN1Integer) IOException(java.io.IOException) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) DSAParameter(org.bouncycastle.asn1.x509.DSAParameter) DSAParameters(org.bouncycastle.crypto.params.DSAParameters) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo)

Example 75 with PrivateKeyInfo

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

the class FillKeytool method generateKeypair.

private static PrivateKeyInfo generateKeypair(String keyspec, SecureRandom random) throws Exception {
    String[] tokens = keyspec.split("/");
    String type = tokens[0];
    switch(type) {
        case "RSA":
            {
                int keysize = Integer.parseInt(tokens[1]);
                if (keysize > 4096) {
                    throw new XiSecurityException("keysize too large");
                }
                KeyPair kp = KeyUtil.generateRSAKeypair(keysize, null, random);
                java.security.interfaces.RSAPublicKey rsaPubKey = (java.security.interfaces.RSAPublicKey) kp.getPublic();
                return KeyUtil.toPrivateKeyInfo((RSAPrivateCrtKey) kp.getPrivate());
            }
        case "EC":
            {
                ASN1ObjectIdentifier curveOid = new ASN1ObjectIdentifier(tokens[1]);
                KeyPair kp = KeyUtil.generateECKeypair(curveOid, random);
                ECPublicKey pub = (ECPublicKey) kp.getPublic();
                int orderBitLength = pub.getParams().getOrder().bitLength();
                byte[] publicKey = KeyUtil.getUncompressedEncodedECPoint(pub.getW(), orderBitLength);
                ECPrivateKey priv = (ECPrivateKey) kp.getPrivate();
                return new PrivateKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, curveOid), new org.bouncycastle.asn1.sec.ECPrivateKey(orderBitLength, priv.getS(), new DERBitString(publicKey), null));
            }
        case "DSA":
            {
                int pLength = Integer.parseInt(tokens[1]);
                int qLength = Integer.parseInt(tokens[2]);
                DSAParameterSpec spec = DSAParameterCache.getDSAParameterSpec(pLength, qLength, null);
                KeyPair kp = KeyUtil.generateDSAKeypair(spec, random);
                DSAParameter parameter = new DSAParameter(spec.getP(), spec.getQ(), spec.getG());
                AlgorithmIdentifier algId = new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa, parameter);
                byte[] publicKey = new ASN1Integer(((DSAPublicKey) kp.getPublic()).getY()).getEncoded();
                // DSA private keys are represented as BER-encoded ASN.1 type INTEGER.
                DSAPrivateKey priv = (DSAPrivateKey) kp.getPrivate();
                return new PrivateKeyInfo(algId, new ASN1Integer(priv.getX()), null, publicKey);
            }
        case "ED25519":
        case "ED448":
        case "X25519":
        case "X448":
            {
                ASN1ObjectIdentifier curveId = EdECConstants.getCurveOid(keyspec);
                KeyPair kp = KeyUtil.generateEdECKeypair(curveId, random);
                return PrivateKeyInfo.getInstance(kp.getPrivate().getEncoded());
            }
        default:
            {
                throw new IllegalArgumentException("unknown keyspec " + keyspec);
            }
    }
}
Also used : DSAParameterSpec(java.security.spec.DSAParameterSpec) KeyPair(java.security.KeyPair) java.security.interfaces(java.security.interfaces) DERBitString(org.bouncycastle.asn1.DERBitString) DERBitString(org.bouncycastle.asn1.DERBitString) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) XiSecurityException(org.xipki.security.XiSecurityException) DSAParameter(org.bouncycastle.asn1.x509.DSAParameter) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo)

Aggregations

PrivateKeyInfo (org.bouncycastle.asn1.pkcs.PrivateKeyInfo)138 IOException (java.io.IOException)95 JcaPEMKeyConverter (org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter)66 PEMParser (org.bouncycastle.openssl.PEMParser)62 PrivateKey (java.security.PrivateKey)48 PEMKeyPair (org.bouncycastle.openssl.PEMKeyPair)41 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)35 PKCS8EncryptedPrivateKeyInfo (org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo)35 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)33 InputDecryptorProvider (org.bouncycastle.operator.InputDecryptorProvider)27 PrivateKeyInfo (com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo)26 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)26 KeyFactory (java.security.KeyFactory)23 JceOpenSSLPKCS8DecryptorProviderBuilder (org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder)21 StringReader (java.io.StringReader)20 BigInteger (java.math.BigInteger)20 KeyPair (java.security.KeyPair)20 AlgorithmIdentifier (com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier)18 ByteArrayInputStream (java.io.ByteArrayInputStream)18 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)18