Search in sources :

Example 76 with PrivateKeyInfo

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

the class P11ProxyResponder method processRequest.

/**
 * The request is constructed as follows.
 * <pre>
 * 0 - - - 1 - - - 2 - - - 3 - - - 4 - - - 5 - - - 6 - - - 7 - - - 8
 * |    Version    |        Transaction ID         |   Body ...    |
 * |   ... Length  |     Action    |   Module ID   |   Content...  |
 * |   .Content               | &lt;-- 10 + Length (offset).
 *
 * </pre>
 *
 * @param pool
 *          The pool that holds the P11CryptService.
 * @param request
 *          The request.
 * @return response.
 */
public byte[] processRequest(LocalP11CryptServicePool pool, byte[] request) {
    int reqLen = request.length;
    // TransactionID
    byte[] transactionId = new byte[4];
    if (reqLen > 5) {
        System.arraycopy(request, 2, transactionId, 0, 4);
    }
    // Action
    short action = ACTION_NOPE;
    if (reqLen > 11) {
        action = IoUtil.parseShort(request, 10);
    }
    if (reqLen < 14) {
        LOG.error("response too short");
        return getResp(VERSION_V1_0, transactionId, RC_BAD_REQUEST, action);
    }
    // Version
    short version = IoUtil.parseShort(request, 0);
    if (!versions.contains(version)) {
        LOG.error("unsupported version {}", version);
        return getResp(VERSION_V1_0, transactionId, RC_UNSUPPORTED_VERSION, action);
    }
    // Length
    int reqBodyLen = IoUtil.parseInt(request, 6);
    if (reqBodyLen + 10 != reqLen) {
        LOG.error("message length unmatch");
        return getResp(version, transactionId, RC_BAD_REQUEST, action);
    }
    short moduleId = IoUtil.parseShort(request, 12);
    int contentLen = reqLen - 14;
    byte[] content;
    if (contentLen == 0) {
        if (actionsRequireNonNullRequest.contains(action)) {
            LOG.error("content is not present but is required");
            return getResp(version, transactionId, RC_BAD_REQUEST, action);
        }
        content = null;
    } else {
        if (actionsRequireNullRequest.contains(action)) {
            LOG.error("content is present but is not permitted");
            return getResp(version, transactionId, RC_BAD_REQUEST, action);
        }
        content = new byte[contentLen];
        System.arraycopy(request, 14, content, 0, contentLen);
    }
    P11CryptService p11CryptService = pool.getP11CryptService(moduleId);
    if (p11CryptService == null) {
        LOG.error("no module {} available", moduleId);
        return getResp(version, transactionId, RC_UNKNOWN_MODULE, action);
    }
    try {
        switch(action) {
            case ACTION_ADD_CERT:
                {
                    AddCertParams asn1 = AddCertParams.getInstance(content);
                    P11Slot slot = getSlot(p11CryptService, asn1.getSlotId());
                    X509Cert cert = new X509Cert(asn1.getCertificate());
                    slot.addCert(cert, asn1.getControl());
                    return getSuccessResp(version, transactionId, action, (byte[]) null);
                }
            case ACTION_DIGEST_SECRETKEY:
                {
                    DigestSecretKeyTemplate template = DigestSecretKeyTemplate.getInstance(content);
                    long mechanism = template.getMechanism().getMechanism();
                    P11Identity identity = p11CryptService.getIdentity(template.getSlotId().getValue(), template.getObjectId().getValue());
                    byte[] hashValue = identity.digestSecretKey(mechanism);
                    ASN1Object obj = new DEROctetString(hashValue);
                    return getSuccessResp(version, transactionId, action, obj);
                }
            case ACTION_GEN_KEYPAIR_DSA:
                {
                    GenDSAKeypairParams asn1 = GenDSAKeypairParams.getInstance(content);
                    P11Slot slot = getSlot(p11CryptService, asn1.getSlotId());
                    P11IdentityId identityId = slot.generateDSAKeypair(asn1.getP(), asn1.getQ(), asn1.getG(), asn1.getControl());
                    ASN1Object obj = new IdentityId(identityId);
                    return getSuccessResp(version, transactionId, action, obj);
                }
            case ACTION_GEN_KEYPAIR_EC:
            case ACTION_GEN_KEYPAIR_EC_EDWARDS:
            case ACTION_GEN_KEYPAIR_EC_MONTGOMERY:
                {
                    GenECKeypairParams asn1 = GenECKeypairParams.getInstance(content);
                    P11Slot slot = getSlot(p11CryptService, asn1.getSlotId());
                    P11IdentityId identityId = slot.generateECKeypair(asn1.getCurveId(), asn1.getControl());
                    ASN1Object obj = new IdentityId(identityId);
                    return getSuccessResp(version, transactionId, action, obj);
                }
            case ACTION_GEN_KEYPAIR_RSA:
                {
                    GenRSAKeypairParams asn1 = GenRSAKeypairParams.getInstance(content);
                    P11Slot slot = getSlot(p11CryptService, asn1.getSlotId());
                    P11IdentityId identityId = slot.generateRSAKeypair(asn1.getKeysize(), asn1.getPublicExponent(), asn1.getControl());
                    ASN1Object obj = new IdentityId(identityId);
                    return getSuccessResp(version, transactionId, action, obj);
                }
            case ACTION_GEN_KEYPAIR_SM2:
                {
                    GenSM2KeypairParams asn1 = GenSM2KeypairParams.getInstance(content);
                    P11Slot slot = getSlot(p11CryptService, asn1.getSlotId());
                    P11IdentityId identityId = slot.generateSM2Keypair(asn1.getControl());
                    ASN1Object obj = new IdentityId(identityId);
                    return getSuccessResp(version, transactionId, action, obj);
                }
            case ACTION_GEN_KEYPAIR_DSA_OTF:
                {
                    GenDSAKeypairParams asn1 = GenDSAKeypairParams.getInstance(content);
                    P11Slot slot = getSlot(p11CryptService, asn1.getSlotId());
                    PrivateKeyInfo ki = slot.generateDSAKeypairOtf(asn1.getP(), asn1.getQ(), asn1.getG());
                    return getSuccessResp(version, transactionId, action, ki.getEncoded());
                }
            case ACTION_GEN_KEYPAIR_EC_OTF:
            case ACTION_GEN_KEYPAIR_EC_EDWARDS_OTF:
            case ACTION_GEN_KEYPAIR_EC_MONTGOMERY_OTF:
                {
                    GenECKeypairParams asn1 = GenECKeypairParams.getInstance(content);
                    P11Slot slot = getSlot(p11CryptService, asn1.getSlotId());
                    PrivateKeyInfo ki = slot.generateECKeypairOtf(asn1.getCurveId());
                    return getSuccessResp(version, transactionId, action, ki.getEncoded());
                }
            case ACTION_GEN_KEYPAIR_RSA_OTF:
                {
                    GenRSAKeypairParams asn1 = GenRSAKeypairParams.getInstance(content);
                    P11Slot slot = getSlot(p11CryptService, asn1.getSlotId());
                    PrivateKeyInfo ki = slot.generateRSAKeypairOtf(asn1.getKeysize(), asn1.getPublicExponent());
                    return getSuccessResp(version, transactionId, action, ki.getEncoded());
                }
            case ACTION_GEN_KEYPAIR_SM2_OTF:
                {
                    GenSM2KeypairParams asn1 = GenSM2KeypairParams.getInstance(content);
                    P11Slot slot = getSlot(p11CryptService, asn1.getSlotId());
                    PrivateKeyInfo ki = slot.generateSM2KeypairOtf();
                    return getSuccessResp(version, transactionId, action, ki.getEncoded());
                }
            case ACTION_GEN_SECRET_KEY:
                {
                    GenSecretKeyParams asn1 = GenSecretKeyParams.getInstance(content);
                    P11Slot slot = getSlot(p11CryptService, asn1.getSlotId());
                    P11IdentityId identityId = slot.generateSecretKey(asn1.getKeyType(), asn1.getKeysize(), asn1.getControl());
                    ASN1Object obj = new IdentityId(identityId);
                    return getSuccessResp(version, transactionId, action, obj);
                }
            case ACTION_GET_CERT:
                {
                    SlotIdAndObjectId identityId = SlotIdAndObjectId.getInstance(content);
                    P11SlotIdentifier slotId = identityId.getSlotId().getValue();
                    P11ObjectIdentifier certId = identityId.getObjectId().getValue();
                    X509Cert cert = p11CryptService.getCert(slotId, certId);
                    if (cert == null) {
                        throw new P11UnknownEntityException(slotId, certId);
                    }
                    return getSuccessResp(version, transactionId, action, cert.getEncoded());
                }
            case ACTION_GET_CERT_IDS:
            case ACTION_GET_PUBLICKEY_IDS:
            case ACTION_GET_IDENTITY_IDS:
                {
                    SlotIdentifier slotId = SlotIdentifier.getInstance(content);
                    P11Slot slot = p11CryptService.getModule().getSlot(slotId.getValue());
                    Set<P11ObjectIdentifier> objectIds;
                    if (ACTION_GET_CERT_IDS == action) {
                        objectIds = slot.getCertIds();
                    } else if (ACTION_GET_IDENTITY_IDS == action) {
                        objectIds = slot.getIdentityKeyIds();
                    } else {
                        Set<P11ObjectIdentifier> identityKeyIds = slot.getIdentityKeyIds();
                        objectIds = new HashSet<>();
                        for (P11ObjectIdentifier identityKeyId : identityKeyIds) {
                            objectIds.add(slot.getIdentity(identityKeyId).getId().getPublicKeyId());
                        }
                    }
                    ASN1EncodableVector vec = new ASN1EncodableVector();
                    for (P11ObjectIdentifier objectId : objectIds) {
                        vec.add(new ObjectIdentifier(objectId));
                    }
                    ASN1Object obj = new DERSequence(vec);
                    return getSuccessResp(version, transactionId, action, obj);
                }
            case ACTION_GET_MECHANISMS:
                {
                    P11SlotIdentifier slotId = SlotIdentifier.getInstance(content).getValue();
                    Set<Long> mechs = p11CryptService.getSlot(slotId).getMechanisms();
                    ASN1EncodableVector vec = new ASN1EncodableVector();
                    for (Long mech : mechs) {
                        vec.add(new ASN1Integer(mech));
                    }
                    ASN1Object obj = new DERSequence(vec);
                    return getSuccessResp(version, transactionId, action, obj);
                }
            case ACTION_GET_PUBLICKEY:
                {
                    SlotIdAndObjectId identityId = SlotIdAndObjectId.getInstance(content);
                    P11SlotIdentifier slotId = identityId.getSlotId().getValue();
                    P11ObjectIdentifier pubKeyId = identityId.getObjectId().getValue();
                    // find out the keyId
                    PublicKey pubKey = null;
                    P11Slot slot = getSlot(p11CryptService, slotId);
                    Set<P11ObjectIdentifier> identityKeyIds = slot.getIdentityKeyIds();
                    for (P11ObjectIdentifier identityKeyId : identityKeyIds) {
                        P11Identity identity = slot.getIdentity(identityKeyId);
                        if (pubKeyId.equals(identity.getId().getPublicKeyId())) {
                            pubKey = identity.getPublicKey();
                        }
                    }
                    if (pubKey == null) {
                        throw new P11UnknownEntityException(slotId, pubKeyId);
                    }
                    ASN1Object obj = KeyUtil.createSubjectPublicKeyInfo(pubKey);
                    return getSuccessResp(version, transactionId, action, obj);
                }
            case ACTION_GET_SERVER_CAPS:
                {
                    boolean readOnly = p11CryptService.getModule().isReadOnly();
                    ASN1Object obj = new ServerCaps(readOnly, versions);
                    return getSuccessResp(version, transactionId, action, obj);
                }
            case ACTION_GET_SLOT_IDS:
                {
                    List<P11SlotIdentifier> slotIds = p11CryptService.getModule().getSlotIds();
                    ASN1EncodableVector vector = new ASN1EncodableVector();
                    for (P11SlotIdentifier slotId : slotIds) {
                        vector.add(new SlotIdentifier(slotId));
                    }
                    ASN1Object obj = new DERSequence(vector);
                    return getSuccessResp(version, transactionId, action, obj);
                }
            case ACTION_IMPORT_SECRET_KEY:
                {
                    ImportSecretKeyParams asn1 = ImportSecretKeyParams.getInstance(content);
                    P11Slot slot = getSlot(p11CryptService, asn1.getSlotId());
                    P11ObjectIdentifier keyId = slot.importSecretKey(asn1.getKeyType(), asn1.getKeyValue(), asn1.getControl());
                    P11IdentityId identityId = new P11IdentityId(asn1.getSlotId(), keyId, null, null);
                    ASN1Object obj = new IdentityId(identityId);
                    return getSuccessResp(version, transactionId, action, obj);
                }
            case ACTION_REMOVE_CERTS:
                {
                    SlotIdAndObjectId asn1 = SlotIdAndObjectId.getInstance(content);
                    P11Slot slot = getSlot(p11CryptService, asn1.getSlotId().getValue());
                    slot.removeCerts(asn1.getObjectId().getValue());
                    return getSuccessResp(version, transactionId, action, (byte[]) null);
                }
            case ACTION_REMOVE_IDENTITY:
                {
                    SlotIdAndObjectId asn1 = SlotIdAndObjectId.getInstance(content);
                    P11Slot slot = getSlot(p11CryptService, asn1.getSlotId().getValue());
                    slot.removeIdentityByKeyId(asn1.getObjectId().getValue());
                    return getSuccessResp(version, transactionId, action, (byte[]) null);
                }
            case ACTION_REMOVE_OBJECTS:
                {
                    RemoveObjectsParams asn1 = RemoveObjectsParams.getInstance(content);
                    P11Slot slot = getSlot(p11CryptService, asn1.getSlotId());
                    int num = slot.removeObjects(asn1.getOjectId(), asn1.getObjectLabel());
                    ASN1Object obj = new ASN1Integer(num);
                    return getSuccessResp(version, transactionId, action, obj);
                }
            case ACTION_SIGN:
                {
                    SignTemplate signTemplate = SignTemplate.getInstance(content);
                    long mechanism = signTemplate.getMechanism().getMechanism();
                    org.xipki.security.pkcs11.proxy.asn1.P11Params asn1Params = signTemplate.getMechanism().getParams();
                    P11Params params = null;
                    if (asn1Params != null) {
                        switch(asn1Params.getTagNo()) {
                            case org.xipki.security.pkcs11.proxy.asn1.P11Params.TAG_RSA_PKCS_PSS:
                                params = RSAPkcsPssParams.getInstance(asn1Params).getPkcsPssParams();
                                break;
                            case org.xipki.security.pkcs11.proxy.asn1.P11Params.TAG_OPAQUE:
                                params = new P11ByteArrayParams(ASN1OctetString.getInstance(asn1Params).getOctets());
                                break;
                            case org.xipki.security.pkcs11.proxy.asn1.P11Params.TAG_IV:
                                params = new P11IVParams(ASN1OctetString.getInstance(asn1Params).getOctets());
                                break;
                            default:
                                throw new BadAsn1ObjectException("unknown SignTemplate.params: unknown tag " + asn1Params.getTagNo());
                        }
                    }
                    byte[] message = signTemplate.getMessage();
                    P11Identity identity = p11CryptService.getIdentity(signTemplate.getSlotId().getValue(), signTemplate.getObjectId().getValue());
                    if (identity == null) {
                        return getResp(version, transactionId, RC_UNKNOWN_ENTITY, action);
                    }
                    byte[] signature = identity.sign(mechanism, params, message);
                    ASN1Object obj = new DEROctetString(signature);
                    return getSuccessResp(version, transactionId, action, obj);
                }
            case ACTION_UPDATE_CERT:
                {
                    ObjectIdAndCert asn1 = ObjectIdAndCert.getInstance(content);
                    P11Slot slot = getSlot(p11CryptService, asn1.getSlotId().getValue());
                    slot.updateCertificate(asn1.getObjectId().getValue(), new X509Cert(asn1.getCertificate()));
                    return getSuccessResp(version, transactionId, action, (byte[]) null);
                }
            default:
                {
                    LOG.error("unsupported XiPKI action code '{}'", action);
                    return getResp(version, transactionId, RC_UNSUPPORTED_ACTION, action);
                }
        }
    } catch (BadAsn1ObjectException ex) {
        LogUtil.error(LOG, ex, "could not process decode requested content (tid=" + Hex.encode(transactionId) + ")");
        return getResp(version, transactionId, RC_BAD_REQUEST, action);
    } catch (P11TokenException ex) {
        LogUtil.error(LOG, ex, buildErrorMsg(action, transactionId));
        short rc;
        if (ex instanceof P11UnknownEntityException) {
            rc = RC_UNKNOWN_ENTITY;
        } else if (ex instanceof P11DuplicateEntityException) {
            rc = RC_DUPLICATE_ENTITY;
        } else if (ex instanceof P11UnsupportedMechanismException) {
            rc = RC_UNSUPPORTED_MECHANISM;
        } else {
            rc = RC_P11_TOKENERROR;
        }
        return getResp(version, transactionId, rc, action);
    } catch (Throwable th) {
        LogUtil.error(LOG, th, buildErrorMsg(action, transactionId));
        return getResp(version, transactionId, RC_INTERNAL_ERROR, action);
    }
}
Also used : P11Params(org.xipki.security.pkcs11.P11Params) List(java.util.List) PublicKey(java.security.PublicKey) P11IVParams(org.xipki.security.pkcs11.P11Params.P11IVParams) Set(java.util.Set) HashSet(java.util.HashSet) P11ByteArrayParams(org.xipki.security.pkcs11.P11Params.P11ByteArrayParams) X509Cert(org.xipki.security.X509Cert) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) BadAsn1ObjectException(org.xipki.security.BadAsn1ObjectException)

Example 77 with PrivateKeyInfo

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

the class CmpCaClient method parseEnrollCertResult.

// method transmit
private Map<BigInteger, KeyAndCert> parseEnrollCertResult(PKIMessage response, int resonseBodyType, int numCerts) throws Exception {
    PKIBody respBody = response.getBody();
    final int bodyType = respBody.getType();
    if (PKIBody.TYPE_ERROR == bodyType) {
        ErrorMsgContent content = ErrorMsgContent.getInstance(respBody.getContent());
        throw new Exception("Server returned PKIStatus: " + buildText(content.getPKIStatusInfo()));
    } else if (resonseBodyType != bodyType) {
        throw new Exception(String.format("unknown PKI body type %s instead the expected [%s, %s]", bodyType, resonseBodyType, PKIBody.TYPE_ERROR));
    }
    CertRepMessage certRep = CertRepMessage.getInstance(respBody.getContent());
    CertResponse[] certResponses = certRep.getResponse();
    if (certResponses.length != numCerts) {
        throw new Exception("expected " + numCerts + " CertResponse, but returned " + certResponses.length);
    }
    // We only accept the certificates which are requested.
    Map<BigInteger, KeyAndCert> keycerts = new HashMap<>(numCerts * 2);
    for (int i = 0; i < numCerts; i++) {
        CertResponse certResp = certResponses[i];
        PKIStatusInfo statusInfo = certResp.getStatus();
        int status = statusInfo.getStatus().intValue();
        BigInteger certReqId = certResp.getCertReqId().getValue();
        if (status != PKIStatus.GRANTED && status != PKIStatus.GRANTED_WITH_MODS) {
            throw new Exception("CertReqId " + certReqId + ": server returned PKIStatus: " + buildText(statusInfo));
        }
        CertifiedKeyPair cvk = certResp.getCertifiedKeyPair();
        if (cvk != null) {
            CMPCertificate cmpCert = cvk.getCertOrEncCert().getCertificate();
            X509Certificate cert = SdkUtil.parseCert(cmpCert.getX509v3PKCert().getEncoded());
            if (!verify(caCert, cert)) {
                throw new Exception("CertReqId " + certReqId + ": the returned certificate is not issued by the given CA");
            }
            EncryptedKey encKey = cvk.getPrivateKey();
            PrivateKeyInfo key = null;
            if (encKey != null) {
                byte[] keyBytes = decrypt(encKey);
                key = PrivateKeyInfo.getInstance(keyBytes);
            }
            keycerts.put(certReqId, new KeyAndCert(key, cert));
        }
    }
    return keycerts;
}
Also used : OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) BigInteger(java.math.BigInteger) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo)

Example 78 with PrivateKeyInfo

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

the class Crypto method loadPrivateKey.

public static PrivateKey loadPrivateKey(Reader reader, String pwd) throws CryptoException {
    try (PEMParser pemReader = new PEMParser(reader)) {
        PrivateKey privKey = null;
        X9ECParameters ecParam = null;
        Object pemObj = pemReader.readObject();
        if (pemObj instanceof ASN1ObjectIdentifier) {
            // make sure this is EC Parameter we're handling. In which case
            // we'll store it and read the next object which should be our
            // EC Private Key
            ASN1ObjectIdentifier ecOID = (ASN1ObjectIdentifier) pemObj;
            ecParam = ECNamedCurveTable.getByOID(ecOID);
            if (ecParam == null) {
                throw new PEMException("Unable to find EC Parameter for the given curve oid: " + ((ASN1ObjectIdentifier) pemObj).getId());
            }
            pemObj = pemReader.readObject();
        } else if (pemObj instanceof X9ECParameters) {
            ecParam = (X9ECParameters) pemObj;
            pemObj = pemReader.readObject();
        }
        if (pemObj instanceof PEMKeyPair) {
            PrivateKeyInfo pKeyInfo = ((PEMKeyPair) pemObj).getPrivateKeyInfo();
            JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter();
            privKey = pemConverter.getPrivateKey(pKeyInfo);
        } else if (pemObj instanceof PKCS8EncryptedPrivateKeyInfo) {
            PKCS8EncryptedPrivateKeyInfo pKeyInfo = (PKCS8EncryptedPrivateKeyInfo) pemObj;
            if (pwd == null) {
                throw new CryptoException("No password specified to decrypt encrypted private key");
            }
            // Decrypt the private key with the specified password
            InputDecryptorProvider pkcs8Prov = new JceOpenSSLPKCS8DecryptorProviderBuilder().setProvider(BC_PROVIDER).build(pwd.toCharArray());
            PrivateKeyInfo privateKeyInfo = pKeyInfo.decryptPrivateKeyInfo(pkcs8Prov);
            JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter();
            privKey = pemConverter.getPrivateKey(privateKeyInfo);
        }
        if (ecParam != null && privKey != null && ECDSA.equals(privKey.getAlgorithm())) {
            ECParameterSpec ecSpec = new ECParameterSpec(ecParam.getCurve(), ecParam.getG(), ecParam.getN(), ecParam.getH(), ecParam.getSeed());
            KeyFactory keyFactory = KeyFactory.getInstance(getECDSAAlgo(), getKeyFactoryProvider());
            ECPrivateKeySpec keySpec = new ECPrivateKeySpec(((BCECPrivateKey) privKey).getS(), ecSpec);
            privKey = keyFactory.generatePrivate(keySpec);
        }
        return privKey;
    } catch (PEMException e) {
        LOG.error("loadPrivateKey: Caught PEMException, problem with format of key detected.");
        throw new CryptoException(e);
    } catch (NoSuchProviderException e) {
        LOG.error("loadPrivateKey: Caught NoSuchProviderException, check to make sure the provider is loaded correctly.");
        throw new CryptoException(e);
    } catch (NoSuchAlgorithmException e) {
        LOG.error("loadPrivateKey: Caught NoSuchAlgorithmException, check to make sure the algorithm is supported by the provider.");
        throw new CryptoException(e);
    } catch (InvalidKeySpecException e) {
        LOG.error("loadPrivateKey: Caught InvalidKeySpecException, invalid key spec is being used.");
        throw new CryptoException(e);
    } catch (OperatorCreationException e) {
        LOG.error("loadPrivateKey: Caught OperatorCreationException when creating JceOpenSSLPKCS8DecryptorProviderBuilder.");
        throw new CryptoException(e);
    } catch (PKCSException e) {
        LOG.error("loadPrivateKey: Caught PKCSException when decrypting private key.");
        throw new CryptoException(e);
    } catch (IOException e) {
        LOG.error("loadPrivateKey: Caught IOException, while trying to read key.");
        throw new CryptoException(e);
    }
}
Also used : BCECPrivateKey(org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey) ECPrivateKeySpec(org.bouncycastle.jce.spec.ECPrivateKeySpec) X9ECParameters(org.bouncycastle.asn1.x9.X9ECParameters) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo) PKCSException(org.bouncycastle.pkcs.PKCSException) PEMParser(org.bouncycastle.openssl.PEMParser) InputDecryptorProvider(org.bouncycastle.operator.InputDecryptorProvider) ECParameterSpec(org.bouncycastle.jce.spec.ECParameterSpec) PEMException(org.bouncycastle.openssl.PEMException) PemObject(org.bouncycastle.util.io.pem.PemObject) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) JceOpenSSLPKCS8DecryptorProviderBuilder(org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo)

Example 79 with PrivateKeyInfo

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

the class RadixKeyStore method encodePrivKey.

/**
 * Encodes the specified raw secp256k1 private key into an ASN.1 encoded <a
 * href="https://tools.ietf.org/html/rfc5208#section-5">Private Key Info</a> structure.
 *
 * <p>Note that the encoded key will not include a public key.
 *
 * @param rawkey The raw secp256k1 private key.
 * @return The ASN.1 encoded private key.
 * @throws IOException If an error occurs encoding the ASN.1 key.
 */
private static byte[] encodePrivKey(byte[] rawkey) throws IOException {
    AlgorithmIdentifier ecSecp256k1 = new AlgorithmIdentifier(OID_EC_ENCRYPTION, OID_SECP256K1_CURVE);
    BigInteger key = new BigInteger(1, rawkey);
    ECPrivateKey privateKey = new ECPrivateKey(ECKeyPair.BYTES * Byte.SIZE, key, OID_SECP256K1_CURVE);
    PrivateKeyInfo pki = new PrivateKeyInfo(ecSecp256k1, privateKey);
    return pki.getEncoded();
}
Also used : ECPrivateKey(org.bouncycastle.asn1.sec.ECPrivateKey) BigInteger(java.math.BigInteger) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier)

Example 80 with PrivateKeyInfo

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

the class PrivateKeyInfoFactory method createPrivateKeyInfo.

/**
 * Create a PrivateKeyInfo representation of a private key with attributes.
 *
 * @param privateKey the key to be encoded into the info object.
 * @param attributes the set of attributes to be included.
 * @return the appropriate PrivateKeyInfo
 * @throws IOException on an error encoding the key
 */
public static PrivateKeyInfo createPrivateKeyInfo(AsymmetricKeyParameter privateKey, ASN1Set attributes) throws IOException {
    if (privateKey instanceof RSAKeyParameters) {
        RSAPrivateCrtKeyParameters priv = (RSAPrivateCrtKeyParameters) privateKey;
        return new PrivateKeyInfo(new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE), new RSAPrivateKey(priv.getModulus(), priv.getPublicExponent(), priv.getExponent(), priv.getP(), priv.getQ(), priv.getDP(), priv.getDQ(), priv.getQInv()), attributes);
    } else if (privateKey instanceof DSAPrivateKeyParameters) {
        DSAPrivateKeyParameters priv = (DSAPrivateKeyParameters) privateKey;
        DSAParameters params = priv.getParameters();
        return new PrivateKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa, new DSAParameter(params.getP(), params.getQ(), params.getG())), new ASN1Integer(priv.getX()), attributes);
    } else if (privateKey instanceof ECPrivateKeyParameters) {
        ECPrivateKeyParameters priv = (ECPrivateKeyParameters) privateKey;
        ECDomainParameters domainParams = priv.getParameters();
        ASN1Encodable params;
        int orderBitLength;
        if (domainParams == null) {
            // Implicitly CA
            params = new X962Parameters(DERNull.INSTANCE);
            orderBitLength = priv.getD().bitLength();
        } else if (domainParams instanceof ECGOST3410Parameters) {
            GOST3410PublicKeyAlgParameters gostParams = new GOST3410PublicKeyAlgParameters(((ECGOST3410Parameters) domainParams).getPublicKeyParamSet(), ((ECGOST3410Parameters) domainParams).getDigestParamSet(), ((ECGOST3410Parameters) domainParams).getEncryptionParamSet());
            int size;
            ASN1ObjectIdentifier identifier;
            if (cryptoProOids.contains(gostParams.getPublicKeyParamSet())) {
                size = 32;
                identifier = CryptoProObjectIdentifiers.gostR3410_2001;
            } else {
                boolean is512 = priv.getD().bitLength() > 256;
                identifier = (is512) ? RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512 : RosstandartObjectIdentifiers.id_tc26_gost_3410_12_256;
                size = (is512) ? 64 : 32;
            }
            byte[] encKey = new byte[size];
            extractBytes(encKey, size, 0, priv.getD());
            return new PrivateKeyInfo(new AlgorithmIdentifier(identifier, gostParams), new DEROctetString(encKey));
        } else if (domainParams instanceof ECNamedDomainParameters) {
            params = new X962Parameters(((ECNamedDomainParameters) domainParams).getName());
            orderBitLength = domainParams.getN().bitLength();
        } else {
            X9ECParameters ecP = new X9ECParameters(domainParams.getCurve(), new X9ECPoint(domainParams.getG(), false), domainParams.getN(), domainParams.getH(), domainParams.getSeed());
            params = new X962Parameters(ecP);
            orderBitLength = domainParams.getN().bitLength();
        }
        ECPoint q = new FixedPointCombMultiplier().multiply(domainParams.getG(), priv.getD());
        // TODO Support point compression
        DERBitString publicKey = new DERBitString(q.getEncoded(false));
        return new PrivateKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, params), new ECPrivateKey(orderBitLength, priv.getD(), publicKey, params), attributes);
    } else if (privateKey instanceof X448PrivateKeyParameters) {
        X448PrivateKeyParameters key = (X448PrivateKeyParameters) privateKey;
        return new PrivateKeyInfo(new AlgorithmIdentifier(EdECObjectIdentifiers.id_X448), new DEROctetString(key.getEncoded()), attributes, key.generatePublicKey().getEncoded());
    } else if (privateKey instanceof X25519PrivateKeyParameters) {
        X25519PrivateKeyParameters key = (X25519PrivateKeyParameters) privateKey;
        return new PrivateKeyInfo(new AlgorithmIdentifier(EdECObjectIdentifiers.id_X25519), new DEROctetString(key.getEncoded()), attributes, key.generatePublicKey().getEncoded());
    } else if (privateKey instanceof Ed448PrivateKeyParameters) {
        Ed448PrivateKeyParameters key = (Ed448PrivateKeyParameters) privateKey;
        return new PrivateKeyInfo(new AlgorithmIdentifier(EdECObjectIdentifiers.id_Ed448), new DEROctetString(key.getEncoded()), attributes, key.generatePublicKey().getEncoded());
    } else if (privateKey instanceof Ed25519PrivateKeyParameters) {
        Ed25519PrivateKeyParameters key = (Ed25519PrivateKeyParameters) privateKey;
        return new PrivateKeyInfo(new AlgorithmIdentifier(EdECObjectIdentifiers.id_Ed25519), new DEROctetString(key.getEncoded()), attributes, key.generatePublicKey().getEncoded());
    } else {
        throw new IOException("key parameters not recognized");
    }
}
Also used : ECDomainParameters(com.github.zhenwei.core.crypto.params.ECDomainParameters) X9ECParameters(com.github.zhenwei.core.asn1.x9.X9ECParameters) ECGOST3410Parameters(com.github.zhenwei.core.crypto.params.ECGOST3410Parameters) GOST3410PublicKeyAlgParameters(com.github.zhenwei.core.asn1.cryptopro.GOST3410PublicKeyAlgParameters) X25519PrivateKeyParameters(com.github.zhenwei.core.crypto.params.X25519PrivateKeyParameters) Ed448PrivateKeyParameters(com.github.zhenwei.core.crypto.params.Ed448PrivateKeyParameters) Ed25519PrivateKeyParameters(com.github.zhenwei.core.crypto.params.Ed25519PrivateKeyParameters) RSAKeyParameters(com.github.zhenwei.core.crypto.params.RSAKeyParameters) DEROctetString(com.github.zhenwei.core.asn1.DEROctetString) AlgorithmIdentifier(com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier) X962Parameters(com.github.zhenwei.core.asn1.x9.X962Parameters) FixedPointCombMultiplier(com.github.zhenwei.core.math.ec.FixedPointCombMultiplier) DSAParameter(com.github.zhenwei.core.asn1.x509.DSAParameter) ASN1Encodable(com.github.zhenwei.core.asn1.ASN1Encodable) X448PrivateKeyParameters(com.github.zhenwei.core.crypto.params.X448PrivateKeyParameters) ECPrivateKey(com.github.zhenwei.core.asn1.sec.ECPrivateKey) ECNamedDomainParameters(com.github.zhenwei.core.crypto.params.ECNamedDomainParameters) DERBitString(com.github.zhenwei.core.asn1.DERBitString) ASN1Integer(com.github.zhenwei.core.asn1.ASN1Integer) IOException(java.io.IOException) ECPoint(com.github.zhenwei.core.math.ec.ECPoint) X9ECPoint(com.github.zhenwei.core.asn1.x9.X9ECPoint) ECPoint(com.github.zhenwei.core.math.ec.ECPoint) X9ECPoint(com.github.zhenwei.core.asn1.x9.X9ECPoint) ECPrivateKeyParameters(com.github.zhenwei.core.crypto.params.ECPrivateKeyParameters) X9ECPoint(com.github.zhenwei.core.asn1.x9.X9ECPoint) DSAPrivateKeyParameters(com.github.zhenwei.core.crypto.params.DSAPrivateKeyParameters) RSAPrivateKey(com.github.zhenwei.core.asn1.pkcs.RSAPrivateKey) DSAParameters(com.github.zhenwei.core.crypto.params.DSAParameters) PrivateKeyInfo(com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo) ASN1ObjectIdentifier(com.github.zhenwei.core.asn1.ASN1ObjectIdentifier) RSAPrivateCrtKeyParameters(com.github.zhenwei.core.crypto.params.RSAPrivateCrtKeyParameters)

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