Search in sources :

Example 1 with RSAKeyParameters

use of org.bouncycastle.crypto.params.RSAKeyParameters in project xipki by xipki.

the class CmpCaClient method getContentVerifierProvider.

// method verifyProtection
public static ContentVerifierProvider getContentVerifierProvider(PublicKey publicKey) throws InvalidKeyException {
    SdkUtil.requireNonNull("publicKey", publicKey);
    String keyAlg = publicKey.getAlgorithm().toUpperCase();
    DigestAlgorithmIdentifierFinder digAlgFinder = new DefaultDigestAlgorithmIdentifierFinder();
    BcContentVerifierProviderBuilder builder;
    if ("RSA".equals(keyAlg)) {
        builder = new BcRSAContentVerifierProviderBuilder(digAlgFinder);
    } else if ("DSA".equals(keyAlg)) {
        builder = new BcDSAContentVerifierProviderBuilder(digAlgFinder);
    } else if ("EC".equals(keyAlg) || "ECDSA".equals(keyAlg)) {
        builder = new BcECContentVerifierProviderBuilder(digAlgFinder);
    } else {
        throw new InvalidKeyException("unknown key algorithm of the public key " + keyAlg);
    }
    AsymmetricKeyParameter keyParam;
    if (publicKey instanceof RSAPublicKey) {
        RSAPublicKey rsaKey = (RSAPublicKey) publicKey;
        keyParam = new RSAKeyParameters(false, rsaKey.getModulus(), rsaKey.getPublicExponent());
    } else if (publicKey instanceof ECPublicKey) {
        keyParam = ECUtil.generatePublicKeyParameter(publicKey);
    } else if (publicKey instanceof DSAPublicKey) {
        keyParam = DSAUtil.generatePublicKeyParameter(publicKey);
    } else {
        throw new InvalidKeyException("unknown key " + publicKey.getClass().getName());
    }
    try {
        return builder.build(keyParam);
    } catch (OperatorCreationException ex) {
        throw new InvalidKeyException("could not build ContentVerifierProvider: " + ex.getMessage(), ex);
    }
}
Also used : BcRSAContentVerifierProviderBuilder(org.bouncycastle.operator.bc.BcRSAContentVerifierProviderBuilder) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) DigestAlgorithmIdentifierFinder(org.bouncycastle.operator.DigestAlgorithmIdentifierFinder) DefaultDigestAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder) InvalidKeyException(java.security.InvalidKeyException) DefaultDigestAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder) RSAKeyParameters(org.bouncycastle.crypto.params.RSAKeyParameters) DSAPublicKey(java.security.interfaces.DSAPublicKey) BcContentVerifierProviderBuilder(org.bouncycastle.operator.bc.BcContentVerifierProviderBuilder) AsymmetricKeyParameter(org.bouncycastle.crypto.params.AsymmetricKeyParameter) RSAPublicKey(java.security.interfaces.RSAPublicKey) ECPublicKey(java.security.interfaces.ECPublicKey) BcDSAContentVerifierProviderBuilder(org.bouncycastle.operator.bc.BcDSAContentVerifierProviderBuilder) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) BcECContentVerifierProviderBuilder(org.bouncycastle.operator.bc.BcECContentVerifierProviderBuilder)

Example 2 with RSAKeyParameters

use of org.bouncycastle.crypto.params.RSAKeyParameters in project jruby-openssl by jruby.

the class SecurityHelper method verify.

static boolean verify(final X509CRL crl, final PublicKey publicKey, final boolean silent) throws NoSuchAlgorithmException, CRLException, InvalidKeyException, SignatureException {
    if (crl instanceof X509CRLObject) {
        final CertificateList crlList = (CertificateList) getCertificateList(crl);
        final AlgorithmIdentifier tbsSignatureId = crlList.getTBSCertList().getSignature();
        if (!crlList.getSignatureAlgorithm().equals(tbsSignatureId)) {
            if (silent)
                return false;
            throw new CRLException("Signature algorithm on CertificateList does not match TBSCertList.");
        }
        final Signature signature = getSignature(crl.getSigAlgName(), securityProvider);
        signature.initVerify(publicKey);
        signature.update(crl.getTBSCertList());
        if (!signature.verify(crl.getSignature())) {
            if (silent)
                return false;
            throw new SignatureException("CRL does not verify with supplied public key.");
        }
        return true;
    } else {
        try {
            final DigestAlgorithmIdentifierFinder digestAlgFinder = new DefaultDigestAlgorithmIdentifierFinder();
            final ContentVerifierProvider verifierProvider;
            if ("DSA".equalsIgnoreCase(publicKey.getAlgorithm())) {
                BigInteger y = ((DSAPublicKey) publicKey).getY();
                DSAParams params = ((DSAPublicKey) publicKey).getParams();
                DSAParameters parameters = new DSAParameters(params.getP(), params.getQ(), params.getG());
                AsymmetricKeyParameter dsaKey = new DSAPublicKeyParameters(y, parameters);
                verifierProvider = new BcDSAContentVerifierProviderBuilder(digestAlgFinder).build(dsaKey);
            } else {
                BigInteger mod = ((RSAPublicKey) publicKey).getModulus();
                BigInteger exp = ((RSAPublicKey) publicKey).getPublicExponent();
                AsymmetricKeyParameter rsaKey = new RSAKeyParameters(false, mod, exp);
                verifierProvider = new BcRSAContentVerifierProviderBuilder(digestAlgFinder).build(rsaKey);
            }
            return new X509CRLHolder(crl.getEncoded()).isSignatureValid(verifierProvider);
        } catch (OperatorException e) {
            throw new SignatureException(e);
        } catch (CertException e) {
            throw new SignatureException(e);
        }// can happen if the input is DER but does not match expected strucure
         catch (ClassCastException e) {
            throw new SignatureException(e);
        } catch (IOException e) {
            throw new SignatureException(e);
        }
    }
}
Also used : DSAPublicKeyParameters(org.bouncycastle.crypto.params.DSAPublicKeyParameters) X509CRLObject(org.bouncycastle.jce.provider.X509CRLObject) BcRSAContentVerifierProviderBuilder(org.bouncycastle.operator.bc.BcRSAContentVerifierProviderBuilder) CertificateList(org.bouncycastle.asn1.x509.CertificateList) CertException(org.bouncycastle.cert.CertException) SignatureException(java.security.SignatureException) DSAParams(java.security.interfaces.DSAParams) IOException(java.io.IOException) DigestAlgorithmIdentifierFinder(org.bouncycastle.operator.DigestAlgorithmIdentifierFinder) DefaultDigestAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder) DefaultDigestAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder) RSAKeyParameters(org.bouncycastle.crypto.params.RSAKeyParameters) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) DSAPublicKey(java.security.interfaces.DSAPublicKey) AsymmetricKeyParameter(org.bouncycastle.crypto.params.AsymmetricKeyParameter) RSAPublicKey(java.security.interfaces.RSAPublicKey) Signature(java.security.Signature) X509CRLHolder(org.bouncycastle.cert.X509CRLHolder) BigInteger(java.math.BigInteger) BcDSAContentVerifierProviderBuilder(org.bouncycastle.operator.bc.BcDSAContentVerifierProviderBuilder) CRLException(java.security.cert.CRLException) DSAParameters(org.bouncycastle.crypto.params.DSAParameters) OperatorException(org.bouncycastle.operator.OperatorException) ContentVerifierProvider(org.bouncycastle.operator.ContentVerifierProvider)

Example 3 with RSAKeyParameters

use of org.bouncycastle.crypto.params.RSAKeyParameters in project cloudbreak by hortonworks.

the class PkiUtil method generateSignature.

public static String generateSignature(String privateKeyPem, byte[] data) {
    RSAKeyParameters rsaKeyParameters = CACHE.get(privateKeyPem);
    if (rsaKeyParameters == null) {
        try (PEMParser pEMParser = new PEMParser(new StringReader(clarifyPemKey(privateKeyPem)))) {
            PEMKeyPair pemKeyPair = (PEMKeyPair) pEMParser.readObject();
            KeyFactory factory = KeyFactory.getInstance("RSA");
            KeySpec publicKeySpec = new X509EncodedKeySpec(pemKeyPair.getPublicKeyInfo().getEncoded());
            PublicKey publicKey = factory.generatePublic(publicKeySpec);
            KeySpec privateKeySpec = new PKCS8EncodedKeySpec(pemKeyPair.getPrivateKeyInfo().getEncoded());
            PrivateKey privateKey = factory.generatePrivate(privateKeySpec);
            KeyPair kp = new KeyPair(publicKey, privateKey);
            RSAPrivateKeySpec privKeySpec = factory.getKeySpec(kp.getPrivate(), RSAPrivateKeySpec.class);
            rsaKeyParameters = new RSAKeyParameters(true, privKeySpec.getModulus(), privKeySpec.getPrivateExponent());
            CACHE.put(privateKeyPem, rsaKeyParameters);
        } catch (NoSuchAlgorithmException | IOException | InvalidKeySpecException e) {
            throw new SecurityException(e);
        }
    }
    Signer signer = new PSSSigner(new RSAEngine(), new SHA256Digest(), SALT_LENGTH);
    signer.init(true, rsaKeyParameters);
    signer.update(data, 0, data.length);
    try {
        byte[] signature = signer.generateSignature();
        return BaseEncoding.base64().encode(signature);
    } catch (CryptoException e) {
        throw new SecurityException(e);
    }
}
Also used : KeyPair(java.security.KeyPair) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) PrivateKey(java.security.PrivateKey) RSAPublicKey(java.security.interfaces.RSAPublicKey) PublicKey(java.security.PublicKey) KeySpec(java.security.spec.KeySpec) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) RSAPrivateKeySpec(java.security.spec.RSAPrivateKeySpec) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) RSAKeyParameters(org.bouncycastle.crypto.params.RSAKeyParameters) Signer(org.bouncycastle.crypto.Signer) ContentSigner(org.bouncycastle.operator.ContentSigner) PSSSigner(org.bouncycastle.crypto.signers.PSSSigner) PEMParser(org.bouncycastle.openssl.PEMParser) RSAPrivateKeySpec(java.security.spec.RSAPrivateKeySpec) SHA256Digest(org.bouncycastle.crypto.digests.SHA256Digest) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) StringReader(java.io.StringReader) PSSSigner(org.bouncycastle.crypto.signers.PSSSigner) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) CryptoException(org.bouncycastle.crypto.CryptoException) RSAEngine(org.bouncycastle.crypto.engines.RSAEngine) PrivateKeyFactory(org.bouncycastle.crypto.util.PrivateKeyFactory) KeyFactory(java.security.KeyFactory)

Example 4 with RSAKeyParameters

use of org.bouncycastle.crypto.params.RSAKeyParameters in project robovm by robovm.

the class PublicKeyFactory method createKey.

/**
     * Create a public key from the passed in SubjectPublicKeyInfo
     * 
     * @param keyInfo the SubjectPublicKeyInfo containing the key data
     * @return the appropriate key parameter
     * @throws IOException on an error decoding the key
     */
public static AsymmetricKeyParameter createKey(SubjectPublicKeyInfo keyInfo) throws IOException {
    AlgorithmIdentifier algId = keyInfo.getAlgorithm();
    if (algId.getAlgorithm().equals(PKCSObjectIdentifiers.rsaEncryption) || algId.getAlgorithm().equals(X509ObjectIdentifiers.id_ea_rsa)) {
        RSAPublicKey pubKey = RSAPublicKey.getInstance(keyInfo.parsePublicKey());
        return new RSAKeyParameters(false, pubKey.getModulus(), pubKey.getPublicExponent());
    } else if (algId.getAlgorithm().equals(X9ObjectIdentifiers.dhpublicnumber)) {
        DHPublicKey dhPublicKey = DHPublicKey.getInstance(keyInfo.parsePublicKey());
        BigInteger y = dhPublicKey.getY().getValue();
        DHDomainParameters dhParams = DHDomainParameters.getInstance(algId.getParameters());
        BigInteger p = dhParams.getP().getValue();
        BigInteger g = dhParams.getG().getValue();
        BigInteger q = dhParams.getQ().getValue();
        BigInteger j = null;
        if (dhParams.getJ() != null) {
            j = dhParams.getJ().getValue();
        }
        DHValidationParameters validation = null;
        DHValidationParms dhValidationParms = dhParams.getValidationParms();
        if (dhValidationParms != null) {
            byte[] seed = dhValidationParms.getSeed().getBytes();
            BigInteger pgenCounter = dhValidationParms.getPgenCounter().getValue();
            // TODO Check pgenCounter size?
            validation = new DHValidationParameters(seed, pgenCounter.intValue());
        }
        return new DHPublicKeyParameters(y, new DHParameters(p, g, q, j, validation));
    } else if (algId.getAlgorithm().equals(PKCSObjectIdentifiers.dhKeyAgreement)) {
        DHParameter params = DHParameter.getInstance(algId.getParameters());
        ASN1Integer derY = (ASN1Integer) keyInfo.parsePublicKey();
        BigInteger lVal = params.getL();
        int l = lVal == null ? 0 : lVal.intValue();
        DHParameters dhParams = new DHParameters(params.getP(), params.getG(), null, l);
        return new DHPublicKeyParameters(derY.getValue(), dhParams);
    } else // END android-removed
    if (algId.getAlgorithm().equals(X9ObjectIdentifiers.id_dsa) || algId.getAlgorithm().equals(OIWObjectIdentifiers.dsaWithSHA1)) {
        ASN1Integer derY = (ASN1Integer) keyInfo.parsePublicKey();
        ASN1Encodable de = algId.getParameters();
        DSAParameters parameters = null;
        if (de != null) {
            DSAParameter params = DSAParameter.getInstance(de.toASN1Primitive());
            parameters = new DSAParameters(params.getP(), params.getQ(), params.getG());
        }
        return new DSAPublicKeyParameters(derY.getValue(), parameters);
    } else if (algId.getAlgorithm().equals(X9ObjectIdentifiers.id_ecPublicKey)) {
        X962Parameters params = new X962Parameters((ASN1Primitive) algId.getParameters());
        X9ECParameters x9;
        if (params.isNamedCurve()) {
            ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) params.getParameters();
            x9 = X962NamedCurves.getByOID(oid);
            if (x9 == null) {
                x9 = SECNamedCurves.getByOID(oid);
                if (x9 == null) {
                    x9 = NISTNamedCurves.getByOID(oid);
                // BEGIN android-removed
                // if (x9 == null)
                // {
                //     x9 = TeleTrusTNamedCurves.getByOID(oid);
                // }
                // END android-removed
                }
            }
        } else {
            x9 = X9ECParameters.getInstance(params.getParameters());
        }
        ASN1OctetString key = new DEROctetString(keyInfo.getPublicKeyData().getBytes());
        X9ECPoint derQ = new X9ECPoint(x9.getCurve(), key);
        // TODO We lose any named parameters here
        ECDomainParameters dParams = new ECDomainParameters(x9.getCurve(), x9.getG(), x9.getN(), x9.getH(), x9.getSeed());
        return new ECPublicKeyParameters(derQ.getPoint(), dParams);
    } else {
        throw new RuntimeException("algorithm identifier in key not recognised");
    }
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DHPublicKeyParameters(org.bouncycastle.crypto.params.DHPublicKeyParameters) ECDomainParameters(org.bouncycastle.crypto.params.ECDomainParameters) DHPublicKey(org.bouncycastle.asn1.x9.DHPublicKey) X9ECParameters(org.bouncycastle.asn1.x9.X9ECParameters) DHValidationParms(org.bouncycastle.asn1.x9.DHValidationParms) ECPublicKeyParameters(org.bouncycastle.crypto.params.ECPublicKeyParameters) RSAKeyParameters(org.bouncycastle.crypto.params.RSAKeyParameters) DEROctetString(org.bouncycastle.asn1.DEROctetString) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) X962Parameters(org.bouncycastle.asn1.x9.X962Parameters) RSAPublicKey(org.bouncycastle.asn1.pkcs.RSAPublicKey) DHValidationParameters(org.bouncycastle.crypto.params.DHValidationParameters) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) DSAParameter(org.bouncycastle.asn1.x509.DSAParameter) DHParameter(org.bouncycastle.asn1.pkcs.DHParameter) DSAPublicKeyParameters(org.bouncycastle.crypto.params.DSAPublicKeyParameters) DHParameters(org.bouncycastle.crypto.params.DHParameters) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) X9ECPoint(org.bouncycastle.asn1.x9.X9ECPoint) X9ECPoint(org.bouncycastle.asn1.x9.X9ECPoint) BigInteger(java.math.BigInteger) DHDomainParameters(org.bouncycastle.asn1.x9.DHDomainParameters) DSAParameters(org.bouncycastle.crypto.params.DSAParameters) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 5 with RSAKeyParameters

use of org.bouncycastle.crypto.params.RSAKeyParameters in project robovm by robovm.

the class RSAKeyPairGenerator method generateKeyPair.

public AsymmetricCipherKeyPair generateKeyPair() {
    BigInteger p, q, n, d, e, pSub1, qSub1, phi;
    //
    // p and q values should have a length of half the strength in bits
    //
    int strength = param.getStrength();
    int pbitlength = (strength + 1) / 2;
    int qbitlength = strength - pbitlength;
    int mindiffbits = strength / 3;
    e = param.getPublicExponent();
    //
    for (; ; ) {
        p = new BigInteger(pbitlength, 1, param.getRandom());
        if (p.mod(e).equals(ONE)) {
            continue;
        }
        if (!p.isProbablePrime(param.getCertainty())) {
            continue;
        }
        if (e.gcd(p.subtract(ONE)).equals(ONE)) {
            break;
        }
    }
    //
    for (; ; ) {
        //
        for (; ; ) {
            q = new BigInteger(qbitlength, 1, param.getRandom());
            if (q.subtract(p).abs().bitLength() < mindiffbits) {
                continue;
            }
            if (q.mod(e).equals(ONE)) {
                continue;
            }
            if (!q.isProbablePrime(param.getCertainty())) {
                continue;
            }
            if (e.gcd(q.subtract(ONE)).equals(ONE)) {
                break;
            }
        }
        //
        // calculate the modulus
        //
        n = p.multiply(q);
        if (n.bitLength() == param.getStrength()) {
            break;
        }
        //
        // if we get here our primes aren't big enough, make the largest
        // of the two p and try again
        //
        p = p.max(q);
    }
    if (p.compareTo(q) < 0) {
        phi = p;
        p = q;
        q = phi;
    }
    pSub1 = p.subtract(ONE);
    qSub1 = q.subtract(ONE);
    phi = pSub1.multiply(qSub1);
    //
    // calculate the private exponent
    //
    d = e.modInverse(phi);
    //
    // calculate the CRT factors
    //
    BigInteger dP, dQ, qInv;
    dP = d.remainder(pSub1);
    dQ = d.remainder(qSub1);
    qInv = q.modInverse(p);
    return new AsymmetricCipherKeyPair(new RSAKeyParameters(false, n, e), new RSAPrivateCrtKeyParameters(n, e, d, p, q, dP, dQ, qInv));
}
Also used : BigInteger(java.math.BigInteger) RSAKeyParameters(org.bouncycastle.crypto.params.RSAKeyParameters) AsymmetricCipherKeyPair(org.bouncycastle.crypto.AsymmetricCipherKeyPair) RSAPrivateCrtKeyParameters(org.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters)

Aggregations

RSAKeyParameters (org.bouncycastle.crypto.params.RSAKeyParameters)11 BigInteger (java.math.BigInteger)6 RSAPublicKey (java.security.interfaces.RSAPublicKey)4 DEROctetString (org.bouncycastle.asn1.DEROctetString)4 DSAParameters (org.bouncycastle.crypto.params.DSAParameters)4 DSAPublicKeyParameters (org.bouncycastle.crypto.params.DSAPublicKeyParameters)4 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)3 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)3 AsymmetricCipherKeyPair (org.bouncycastle.crypto.AsymmetricCipherKeyPair)3 ECDomainParameters (org.bouncycastle.crypto.params.ECDomainParameters)3 ECPublicKeyParameters (org.bouncycastle.crypto.params.ECPublicKeyParameters)3 RSAPrivateCrtKeyParameters (org.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters)3 IOException (java.io.IOException)2 KeyFactory (java.security.KeyFactory)2 KeyPair (java.security.KeyPair)2 DSAPublicKey (java.security.interfaces.DSAPublicKey)2 KeySpec (java.security.spec.KeySpec)2 DHParameter (org.bouncycastle.asn1.pkcs.DHParameter)2 DSAParameter (org.bouncycastle.asn1.x509.DSAParameter)2 DHDomainParameters (org.bouncycastle.asn1.x9.DHDomainParameters)2