Search in sources :

Example 61 with RSAPublicKey

use of java.security.interfaces.RSAPublicKey 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 62 with RSAPublicKey

use of java.security.interfaces.RSAPublicKey in project jruby-openssl by jruby.

the class X509Cert method to_text.

@JRubyMethod
public IRubyObject to_text(final ThreadContext context) {
    final Ruby runtime = context.runtime;
    final char[] S20 = StringHelper.S20;
    final StringBuilder text = new StringBuilder(240);
    text.append("Certificate:\n");
    text.append(S20, 0, 4).append("Data:\n");
    final int version = this.version == null ? 0 : RubyNumeric.fix2int(this.version);
    text.append(S20, 0, 8).append("Version: ").append(version + 1).append(" (0x").append(Integer.toString(version, 16)).append(")\n");
    // <= 0x1122334455667788 printed on same line as :
    // Serial Number: 1234605616436508552 (0x1122334455667788)
    // but 0x112233445566778899 ends up :
    // Serial Number:
    // 11:22:33:44:55:66:77:88:99
    text.append(S20, 0, 8).append("Serial Number:");
    if (serial.compareTo(new BigInteger("FFFFFFFFFFFFFFFF", 16)) > 0) {
        text.append('\n');
        text.append(S20, 0, 12).append(lowerHexBytes(serial.toByteArray(), 1)).append('\n');
    } else {
        text.append(' ').append(serial.toString(10)).append(' ');
        text.append('(').append("0x").append(serial.toString(16)).append(')').append('\n');
    }
    text.append(S20, 0, 4).append("Signature Algorithm: ").append(signature_algorithm()).append('\n');
    // final RubyString issuer = issuer().asString(); ByteList bytes = issuer.getByteList();
    // StringHelper.gsub(runtime, bytes, (byte) '/', (byte) ' ');
    // if ( bytes.charAt(0) == ' ' ) bytes.setBegin(bytes.getBegin() + 1);
    text.append(S20, 0, 8).append("Issuer: ").append(issuer).append('\n');
    text.append(S20, 0, 8).append("Validity\n");
    text.append(S20, 0, 12).append("Not Before: ");
    appendGMTDateTime(text, getNotBefore()).append('\n');
    text.append(S20, 0, 12).append("Not After : ");
    appendGMTDateTime(text, getNotAfter()).append('\n');
    text.append(S20, 0, 8).append("Subject: ").append(subject()).append('\n');
    text.append(S20, 0, 8).append("Subject Public Key Info:\n");
    final PublicKey publicKey = getPublicKey();
    text.append(S20, 0, 12).append("Public Key Algorithm: ").append(publicKey.getAlgorithm()).append('\n');
    if ("RSA".equals(publicKey.getAlgorithm())) {
        final RSAPublicKey rsaKey = ((RSAPublicKey) publicKey);
        text.append(S20, 0, 16).append("Public-Key: (").append(rsaKey.getModulus().bitLength()).append(" bit)\n");
        text.append(S20, 0, 16).append("Modulus:\n");
        appendLowerHexValue(text, rsaKey.getModulus().toByteArray(), 20, 45);
        final BigInteger exponent = rsaKey.getPublicExponent();
        text.append(S20, 0, 16).append("Exponent: ").append(exponent).append(" (0x").append(exponent.toString(16)).append(")\n");
    } else if ("DSA".equals(publicKey.getAlgorithm())) {
        final DSAPublicKey dsaKey = ((DSAPublicKey) publicKey);
        text.append(S20, 0, 16).append("Public-Key: (").append(dsaKey.getY().bitLength()).append(" bit)\n");
        // left-TODO
        text.append(S20, 0, 16).append("TODO: not-implemented (PR HOME-WORK)").append('\n');
    } else {
        // left-TODO
        text.append(S20, 0, 16).append("TODO: not-implemented (PRs WELCOME!)").append('\n');
    }
    if (extensions != null && extensions.size() > 0) {
        text.append(S20, 0, 8).append("X509v3 extensions:\n");
        extensions_to_text(context, extensions, text, 12);
    }
    text.append(S20, 0, 4).append("Signature Algorithm: ").append(signature_algorithm()).append('\n');
    appendLowerHexValue(text, getSignature(), 9, 54);
    return RubyString.newString(runtime, text);
}
Also used : RSAPublicKey(java.security.interfaces.RSAPublicKey) RSAPublicKey(java.security.interfaces.RSAPublicKey) PublicKey(java.security.PublicKey) DSAPublicKey(java.security.interfaces.DSAPublicKey) BigInteger(java.math.BigInteger) Ruby(org.jruby.Ruby) DSAPublicKey(java.security.interfaces.DSAPublicKey) JRubyMethod(org.jruby.anno.JRubyMethod)

Example 63 with RSAPublicKey

use of java.security.interfaces.RSAPublicKey in project jruby-openssl by jruby.

the class PEMInputOutput method readRSAPublicKey.

/**
 * reads an RSA public key encoded in an PKCS#1 RSA structure.
 * c: PEM_read_bio_RSAPublicKey
 */
public static RSAPublicKey readRSAPublicKey(Reader in, char[] f) throws PasswordRequiredException, IOException {
    final BufferedReader reader = makeBuffered(in);
    String line;
    while ((line = reader.readLine()) != null) {
        if (line.indexOf(BEG_STRING_PUBLIC) != -1) {
            try {
                return (RSAPublicKey) readPublicKey(reader, "RSA", BEF_E + PEM_STRING_PUBLIC);
            } catch (Exception e) {
                throw mapReadException("problem creating RSA public key: ", e);
            }
        } else if (line.indexOf(BEF_G + PEM_STRING_RSA_PUBLIC) != -1) {
            try {
                return (RSAPublicKey) readPublicKey(reader, "RSA", BEF_E + PEM_STRING_RSA_PUBLIC);
            } catch (Exception e) {
                throw mapReadException("problem creating RSA public key: ", e);
            }
        }
    }
    return null;
}
Also used : RSAPublicKey(java.security.interfaces.RSAPublicKey) BufferedReader(java.io.BufferedReader) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) DEROctetString(org.bouncycastle.asn1.DEROctetString) GeneralSecurityException(java.security.GeneralSecurityException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) CertificateEncodingException(java.security.cert.CertificateEncodingException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) CMSException(org.bouncycastle.cms.CMSException) InvalidCipherTextException(org.bouncycastle.crypto.InvalidCipherTextException) IOException(java.io.IOException) CRLException(java.security.cert.CRLException) CertificateException(java.security.cert.CertificateException)

Example 64 with RSAPublicKey

use of java.security.interfaces.RSAPublicKey in project ballerina by ballerina-lang.

the class JWTVerifierTest method getRSAPublicKey.

private RSAPublicKey getRSAPublicKey() throws Exception {
    KeyStore trustStore;
    InputStream file = new FileInputStream(new File(getClass().getClassLoader().getResource("datafiles/security/keyStore/ballerinaTruststore.p12").getPath()));
    trustStore = java.security.KeyStore.getInstance("pkcs12");
    trustStore.load(file, "ballerina".toCharArray());
    Certificate publicCertificate = trustStore.getCertificate("ballerina");
    return (RSAPublicKey) publicCertificate.getPublicKey();
}
Also used : RSAPublicKey(java.security.interfaces.RSAPublicKey) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) KeyStore(java.security.KeyStore) File(java.io.File) FileInputStream(java.io.FileInputStream) Certificate(java.security.cert.Certificate)

Example 65 with RSAPublicKey

use of java.security.interfaces.RSAPublicKey in project ballerina by ballerina-lang.

the class JWTVerifierTest method testRSA256Verifier.

@Test(description = "Test RSAVerifier with SHA-256 hashing ")
public void testRSA256Verifier() throws Exception {
    String data = "ewogICJhbGciOiAiUlMyNTYiLAogICJ0eXAiOiAiSldUIgp9.ewogICJzdWIiOiAiMTIzNjU0IiwKICAibmFtZSI6ICJK" + "b2huIiwKICAiaXNzIjogIndzbzIiLAogICJhdWQiOiAiYmFsbGVyaW5hIiwKICAiZXhwIjogMTUxOTk5NDU2NDI0OQp9";
    String signature = "X10zu93zSfo0TJQdyDrWZEr5RfX-8vA3dNuxkVRhhj_v51Q7FQ2WUP_rQpJGL2VyFpu23W1ypXXGiDMqDZodqQ8v" + "cf1ElO_qIC6ls0Ay6fHzjpLQdVU7bkFfpuqoboXfOSLCxwzHnvKNIWqmVBHW7CE4jPjb7_11QpT1CxwIUSXtVFk2" + "Z3gpCyfwCVe_JXtBwDbyCQGO_g2tKUSwHvvNDu3THgCcB2ALIS_JznaK9iPf55YmeNwB_KRGkaY-VLvQ5iUILWp2" + "J5SF3QavfXMNhv8GoEDBe2ZfbQgH5E-TpakoL51Ix8vELiznVl7sbtAqlD97440hW3wXoq68kboCVQ==";
    String algorithm = "RS256";
    RSAPublicKey publicKey = getRSAPublicKey();
    JWSVerifier verifier = new RSAVerifier(publicKey);
    Assert.assertTrue(verifier.verify(data, signature, algorithm));
}
Also used : RSAPublicKey(java.security.interfaces.RSAPublicKey) JWSVerifier(org.ballerinalang.nativeimpl.jwt.crypto.JWSVerifier) RSAVerifier(org.ballerinalang.nativeimpl.jwt.crypto.RSAVerifier) Test(org.testng.annotations.Test)

Aggregations

RSAPublicKey (java.security.interfaces.RSAPublicKey)240 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)65 PublicKey (java.security.PublicKey)50 KeyPair (java.security.KeyPair)48 BigInteger (java.math.BigInteger)44 IOException (java.io.IOException)39 KeyPairGenerator (java.security.KeyPairGenerator)39 KeyFactory (java.security.KeyFactory)37 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)31 ECPublicKey (java.security.interfaces.ECPublicKey)30 X509Certificate (java.security.cert.X509Certificate)29 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)28 X509EncodedKeySpec (java.security.spec.X509EncodedKeySpec)27 Test (org.junit.Test)27 PrivateKey (java.security.PrivateKey)26 RSAPublicKeySpec (java.security.spec.RSAPublicKeySpec)26 CertificateException (java.security.cert.CertificateException)24 DSAPublicKey (java.security.interfaces.DSAPublicKey)24 InvalidKeyException (java.security.InvalidKeyException)22 ByteArrayInputStream (java.io.ByteArrayInputStream)21