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);
}
}
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;
}
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);
}
}
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);
}
}
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);
}
}
}
Aggregations