Example usage for java.security.spec RSAPublicKeySpec RSAPublicKeySpec

List of usage examples for java.security.spec RSAPublicKeySpec RSAPublicKeySpec

Introduction

In this page you can find the example usage for java.security.spec RSAPublicKeySpec RSAPublicKeySpec.

Prototype

public RSAPublicKeySpec(BigInteger modulus, BigInteger publicExponent) 

Source Link

Document

Creates a new RSAPublicKeySpec.

Usage

From source file:org.xdi.oxauth.model.util.JwtUtil.java

public static boolean verifySignatureRS384(byte[] signingInput, byte[] sigBytes, RSAPublicKey rsaPublicKey)
        throws IllegalBlockSizeException, IOException, InvalidKeyException, NoSuchProviderException,
        InvalidKeySpecException, NoSuchAlgorithmException, NoSuchPaddingException, BadPaddingException {
    RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(rsaPublicKey.getModulus(),
            rsaPublicKey.getPublicExponent());

    KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
    PublicKey publicKey = keyFactory.generatePublic(rsaPublicKeySpec);

    Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding", "BC");
    cipher.init(Cipher.DECRYPT_MODE, publicKey);

    byte[] decSig = cipher.doFinal(sigBytes);
    ASN1InputStream aIn = new ASN1InputStream(decSig);
    try {//from  w ww. j  a  v  a 2 s.  c  om
        ASN1Sequence seq = (ASN1Sequence) aIn.readObject();

        MessageDigest hash = MessageDigest.getInstance("SHA-384", "BC");
        hash.update(signingInput);

        ASN1OctetString sigHash = (ASN1OctetString) seq.getObjectAt(1);
        return MessageDigest.isEqual(hash.digest(), sigHash.getOctets());
    } finally {
        IOUtils.closeQuietly(aIn);
    }
}

From source file:ee.ria.xroad.common.util.CryptoUtils.java

/**
 * Generates X509 encoded public key bytes from a given modulus and
 * public exponent./*  w w w  . ja v  a 2 s  . c  om*/
 * @param modulus the modulus
 * @param publicExponent the public exponent
 * @return generated public key bytes
 * @throws Exception if any errors occur
 */
public static byte[] generateX509PublicKey(BigInteger modulus, BigInteger publicExponent) throws Exception {
    RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(modulus, publicExponent);
    PublicKey javaRsaPublicKey = KEY_FACTORY.generatePublic(rsaPublicKeySpec);
    return generateX509PublicKey(javaRsaPublicKey);
}

From source file:org.xdi.oxauth.model.util.JwtUtil.java

public static boolean verifySignatureRS512(byte[] signingInput, byte[] sigBytes, RSAPublicKey rsaPublicKey)
        throws IllegalBlockSizeException, IOException, InvalidKeyException, NoSuchProviderException,
        InvalidKeySpecException, NoSuchAlgorithmException, NoSuchPaddingException, BadPaddingException {
    RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(rsaPublicKey.getModulus(),
            rsaPublicKey.getPublicExponent());

    KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
    PublicKey publicKey = keyFactory.generatePublic(rsaPublicKeySpec);

    Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding", "BC");
    cipher.init(Cipher.DECRYPT_MODE, publicKey);

    byte[] decSig = cipher.doFinal(sigBytes);
    ASN1InputStream aIn = new ASN1InputStream(decSig);
    try {//from w  ww .j  av  a 2  s.c o  m
        ASN1Sequence seq = (ASN1Sequence) aIn.readObject();

        MessageDigest hash = MessageDigest.getInstance("SHA-512", "BC");
        hash.update(signingInput);

        ASN1OctetString sigHash = (ASN1OctetString) seq.getObjectAt(1);
        return MessageDigest.isEqual(hash.digest(), sigHash.getOctets());
    } finally {
        IOUtils.closeQuietly(aIn);
    }
}

From source file:com.orange.oidc.secproxy_service.KryptoUtils.java

public static PublicKey pubKeyFromJwk(String jwkp) {
    PublicKey pubKey = null;//from   ww  w  .  j  av  a  2  s  . c o  m

    try {
        JSONObject jk = new JSONObject(jwkp).getJSONArray("keys").getJSONObject(0);

        BigInteger n = new BigInteger(1, decodeB64(jk.getString("n")));
        BigInteger e = new BigInteger(1, decodeB64(jk.getString("e")));

        // Log.d("pubKeyFromJwk","n "+n);
        // Log.d("pubKeyFromJwk","e "+e);

        RSAPublicKeySpec pubRsaSpec = new RSAPublicKeySpec(n, e);
        KeyFactory keyfact = KeyFactory.getInstance("RSA", "SC");
        pubKey = keyfact.generatePublic(pubRsaSpec);
        // Log.d("pubKeyFromJwk","pub key length "+pubRsaSpec.getModulus().toByteArray().length);

    } catch (Exception e) {
        e.printStackTrace();
    }

    return pubKey;
}

From source file:de.tum.frm2.nicos_android.nicos.NicosClient.java

private PublicKey extractPublicKey(String source) {
    // Java wants the key formatted without prefix and postfix.
    String prefix = "-----BEGIN RSA PUBLIC KEY-----";
    String postfix = "\n-----END RSA PUBLIC KEY-----";

    // Java's string formatting/slicing is... 'slightly' inferior to python's.
    String keyNoPrefix = source.substring(prefix.length());
    String reversed = new StringBuilder(keyNoPrefix).reverse().toString();
    String reversedNoPostfix = reversed.substring(postfix.length());
    String keyString = new StringBuilder(reversedNoPostfix).reverse().toString();
    keyString = keyString.replace("\n", "");

    ASN1InputStream in = new ASN1InputStream(Base64.decode(keyString, Base64.NO_WRAP));
    ASN1Primitive obj;/*from  ww  w. j a  v  a2s. c  o m*/
    try {
        obj = in.readObject();
    } catch (IOException e) {
        return null;
    }

    RSAPublicKey key = RSAPublicKey.getInstance(obj);
    RSAPublicKeySpec keySpec = null;
    if (key != null) {
        keySpec = new RSAPublicKeySpec(key.getModulus(), key.getPublicExponent());
    }

    KeyFactory keyFactory = null;
    try {
        keyFactory = KeyFactory.getInstance("RSA");
    } catch (NoSuchAlgorithmException e) {
        // Cannot happen.
    }

    PublicKey pubkey = null;
    try {
        if (keyFactory != null) {
            pubkey = keyFactory.generatePublic(keySpec);
        }
    } catch (InvalidKeySpecException e) {
        // Cannot (SHOULD NOT) happen.
    }
    return pubkey;
}

From source file:cn.usually.common.pay.union.sdknew.SecureUtil.java

public static PublicKey getPublicKey(String modulus, String exponent) {
    try {/*from   ww  w . j a  va2  s .  c  om*/
        BigInteger b1 = new BigInteger(modulus);
        BigInteger b2 = new BigInteger(exponent);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2);
        return keyFactory.generatePublic(keySpec);
    } catch (Exception e) {
        throw new RuntimeException("getPublicKey error", e);
    }
}

From source file:acp.sdk.SecureUtil.java

public static PublicKey getPublicKey(String modulus, String exponent) {
    try {/*from  w  w  w  .jav a 2 s . c  o m*/
        BigInteger b1 = new BigInteger(modulus);
        BigInteger b2 = new BigInteger(exponent);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
        RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2);
        return keyFactory.generatePublic(keySpec);
    } catch (Exception e) {
        throw new RuntimeException("getPublicKey error", e);
    }
}

From source file:nl.knmi.adaguc.services.oauth2.OAuth2Handler.java

/**
 * RSASSA-PKCS1-V1_5-VERIFY ((n, e), M, S) using SHA-256
 * //from  ww w.j a  v a 2  s  .c  om
 * @param modulus_n
 * @param exponent_e
 * @param signinInput_M
 * @param signature_S
 * @return
 * @throws SignatureException
 * @throws InvalidKeyException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
static boolean RSASSA_PKCS1_V1_5_VERIFY(String modulus_n, String exponent_e, String signinInput_M,
        String signature_S)
        throws SignatureException, InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException {
    Debug.println("Starting verification");
    /* RSA SHA-256 RSASSA-PKCS1-V1_5-VERIFY */
    // Modulus (n from https://www.googleapis.com/oauth2/v2/certs)
    String n = modulus_n;
    // Exponent (e from https://www.googleapis.com/oauth2/v2/certs)
    String e = exponent_e;
    // The JWT Signing Input (JWT Header and JWT Payload concatenated with
    // ".")
    byte[] M = signinInput_M.getBytes();
    // Signature (JWT Crypto)
    byte[] S = Base64.decodeBase64(signature_S);

    byte[] modulusBytes = Base64.decodeBase64(n);
    byte[] exponentBytes = Base64.decodeBase64(e);
    BigInteger modulusInteger = new BigInteger(1, modulusBytes);
    BigInteger exponentInteger = new BigInteger(1, exponentBytes);

    RSAPublicKeySpec rsaPubKey = new RSAPublicKeySpec(modulusInteger, exponentInteger);
    KeyFactory fact = KeyFactory.getInstance("RSA");
    PublicKey pubKey = fact.generatePublic(rsaPubKey);
    Signature signature = Signature.getInstance("SHA256withRSA");
    signature.initVerify(pubKey);
    signature.update(M);
    boolean isVerified = signature.verify(S);
    Debug.println("Verify result [" + isVerified + "]");
    return isVerified;
}

From source file:org.ejbca.util.CertTools.java

public static X509Certificate genSelfCertForPurpose(String dn, long validity, String policyId,
        PrivateKey privKey, PublicKey pubKey, String sigAlg, boolean isCA, int keyusage, String provider)
        throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, CertificateEncodingException,
        IllegalStateException, NoSuchProviderException {
    // Create self signed certificate
    Date firstDate = new Date();

    // Set back startdate ten minutes to avoid some problems with wrongly set clocks.
    firstDate.setTime(firstDate.getTime() - (10 * 60 * 1000));

    Date lastDate = new Date();

    // validity in days = validity*24*60*60*1000 milliseconds
    lastDate.setTime(lastDate.getTime() + (validity * (24 * 60 * 60 * 1000)));

    X509V3CertificateGenerator certgen = new X509V3CertificateGenerator();

    // Transform the PublicKey to be sure we have it in a format that the X509 certificate generator handles, it might be 
    // a CVC public key that is passed as parameter
    PublicKey publicKey = null;//from ww w .jav  a 2s  . co m
    if (pubKey instanceof RSAPublicKey) {
        RSAPublicKey rsapk = (RSAPublicKey) pubKey;
        RSAPublicKeySpec rSAPublicKeySpec = new RSAPublicKeySpec(rsapk.getModulus(), rsapk.getPublicExponent());
        try {
            publicKey = KeyFactory.getInstance("RSA").generatePublic(rSAPublicKeySpec);
        } catch (InvalidKeySpecException e) {
            log.error("Error creating RSAPublicKey from spec: ", e);
            publicKey = pubKey;
        }
    } else if (pubKey instanceof ECPublicKey) {
        ECPublicKey ecpk = (ECPublicKey) pubKey;
        try {
            ECPublicKeySpec ecspec = new ECPublicKeySpec(ecpk.getW(), ecpk.getParams()); // will throw NPE if key is "implicitlyCA"
            publicKey = KeyFactory.getInstance("EC").generatePublic(ecspec);
        } catch (InvalidKeySpecException e) {
            log.error("Error creating ECPublicKey from spec: ", e);
            publicKey = pubKey;
        } catch (NullPointerException e) {
            log.debug("NullPointerException, probably it is implicitlyCA generated keys: " + e.getMessage());
            publicKey = pubKey;
        }
    } else {
        log.debug("Not converting key of class. " + pubKey.getClass().getName());
        publicKey = pubKey;
    }

    // Serialnumber is random bits, where random generator is initialized with Date.getTime() when this
    // bean is created.
    byte[] serno = new byte[8];
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    random.setSeed(new Date().getTime());
    random.nextBytes(serno);
    certgen.setSerialNumber(new java.math.BigInteger(serno).abs());
    certgen.setNotBefore(firstDate);
    certgen.setNotAfter(lastDate);
    certgen.setSignatureAlgorithm(sigAlg);
    certgen.setSubjectDN(CertTools.stringToBcX509Name(dn));
    certgen.setIssuerDN(CertTools.stringToBcX509Name(dn));
    certgen.setPublicKey(publicKey);

    // Basic constranits is always critical and MUST be present at-least in CA-certificates.
    BasicConstraints bc = new BasicConstraints(isCA);
    certgen.addExtension(X509Extensions.BasicConstraints.getId(), true, bc);

    // Put critical KeyUsage in CA-certificates
    if (isCA) {
        X509KeyUsage ku = new X509KeyUsage(keyusage);
        certgen.addExtension(X509Extensions.KeyUsage.getId(), true, ku);
    }

    // Subject and Authority key identifier is always non-critical and MUST be present for certificates to verify in Firefox.
    try {
        if (isCA) {
            SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo(
                    (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(publicKey.getEncoded()))
                            .readObject());
            SubjectKeyIdentifier ski = new SubjectKeyIdentifier(spki);

            SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo(
                    (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(publicKey.getEncoded()))
                            .readObject());
            AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki);

            certgen.addExtension(X509Extensions.SubjectKeyIdentifier.getId(), false, ski);
            certgen.addExtension(X509Extensions.AuthorityKeyIdentifier.getId(), false, aki);
        }
    } catch (IOException e) { // do nothing
    }

    // CertificatePolicies extension if supplied policy ID, always non-critical
    if (policyId != null) {
        PolicyInformation pi = new PolicyInformation(new DERObjectIdentifier(policyId));
        DERSequence seq = new DERSequence(pi);
        certgen.addExtension(X509Extensions.CertificatePolicies.getId(), false, seq);
    }

    X509Certificate selfcert = certgen.generate(privKey, provider);

    return selfcert;
}

From source file:org.cesecore.util.CertTools.java

public static X509Certificate genSelfCertForPurpose(String dn, long validity, String policyId,
        PrivateKey privKey, PublicKey pubKey, String sigAlg, boolean isCA, int keyusage,
        Date privateKeyNotBefore, Date privateKeyNotAfter, String provider, boolean ldapOrder,
        List<Extension> additionalExtensions)
        throws CertificateParsingException, IOException, OperatorCreationException {
    // Create self signed certificate
    Date firstDate = new Date();

    // Set back startdate ten minutes to avoid some problems with wrongly set clocks.
    firstDate.setTime(firstDate.getTime() - (10 * 60 * 1000));

    Date lastDate = new Date();

    // validity in days = validity*24*60*60*1000 milliseconds
    lastDate.setTime(lastDate.getTime() + (validity * (24 * 60 * 60 * 1000)));

    // Transform the PublicKey to be sure we have it in a format that the X509 certificate generator handles, it might be
    // a CVC public key that is passed as parameter
    PublicKey publicKey = null;//from  ww  w. jav  a 2  s . c o  m
    if (pubKey instanceof RSAPublicKey) {
        RSAPublicKey rsapk = (RSAPublicKey) pubKey;
        RSAPublicKeySpec rSAPublicKeySpec = new RSAPublicKeySpec(rsapk.getModulus(), rsapk.getPublicExponent());
        try {
            publicKey = KeyFactory.getInstance("RSA").generatePublic(rSAPublicKeySpec);
        } catch (InvalidKeySpecException e) {
            log.error("Error creating RSAPublicKey from spec: ", e);
            publicKey = pubKey;
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("RSA was not a known algorithm", e);
        }
    } else if (pubKey instanceof ECPublicKey) {
        ECPublicKey ecpk = (ECPublicKey) pubKey;
        try {
            ECPublicKeySpec ecspec = new ECPublicKeySpec(ecpk.getW(), ecpk.getParams()); // will throw NPE if key is "implicitlyCA"
            final String algo = ecpk.getAlgorithm();
            if (algo.equals(AlgorithmConstants.KEYALGORITHM_ECGOST3410)) {
                try {
                    publicKey = KeyFactory.getInstance("ECGOST3410").generatePublic(ecspec);
                } catch (NoSuchAlgorithmException e) {
                    throw new IllegalStateException("ECGOST3410 was not a known algorithm", e);
                }
            } else if (algo.equals(AlgorithmConstants.KEYALGORITHM_DSTU4145)) {
                try {
                    publicKey = KeyFactory.getInstance("DSTU4145").generatePublic(ecspec);
                } catch (NoSuchAlgorithmException e) {
                    throw new IllegalStateException("DSTU4145 was not a known algorithm", e);
                }
            } else {
                try {
                    publicKey = KeyFactory.getInstance("EC").generatePublic(ecspec);
                } catch (NoSuchAlgorithmException e) {
                    throw new IllegalStateException("EC was not a known algorithm", e);
                }
            }
        } catch (InvalidKeySpecException e) {
            log.error("Error creating ECPublicKey from spec: ", e);
            publicKey = pubKey;
        } catch (NullPointerException e) {
            log.debug("NullPointerException, probably it is implicitlyCA generated keys: " + e.getMessage());
            publicKey = pubKey;
        }
    } else {
        log.debug("Not converting key of class. " + pubKey.getClass().getName());
        publicKey = pubKey;
    }

    // Serialnumber is random bits, where random generator is initialized with Date.getTime() when this
    // bean is created.
    byte[] serno = new byte[8];
    SecureRandom random;
    try {
        random = SecureRandom.getInstance("SHA1PRNG");
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException("SHA1PRNG was not a known algorithm", e);
    }
    random.setSeed(new Date().getTime());
    random.nextBytes(serno);

    SubjectPublicKeyInfo pkinfo;
    try {
        pkinfo = new SubjectPublicKeyInfo((ASN1Sequence) ASN1Primitive.fromByteArray(publicKey.getEncoded()));
    } catch (IOException e) {
        throw new IllegalArgumentException("Provided public key could not be read to ASN1Primitive", e);
    }
    X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder(
            CertTools.stringToBcX500Name(dn, ldapOrder), new BigInteger(serno).abs(), firstDate, lastDate,
            CertTools.stringToBcX500Name(dn, ldapOrder), pkinfo);

    // Basic constranits is always critical and MUST be present at-least in CA-certificates.
    BasicConstraints bc = new BasicConstraints(isCA);
    certbuilder.addExtension(Extension.basicConstraints, true, bc);

    // Put critical KeyUsage in CA-certificates
    if (isCA || keyusage != 0) {
        X509KeyUsage ku = new X509KeyUsage(keyusage);
        certbuilder.addExtension(Extension.keyUsage, true, ku);
    }

    if ((privateKeyNotBefore != null) || (privateKeyNotAfter != null)) {
        final ASN1EncodableVector v = new ASN1EncodableVector();
        if (privateKeyNotBefore != null) {
            v.add(new DERTaggedObject(false, 0, new DERGeneralizedTime(privateKeyNotBefore)));
        }
        if (privateKeyNotAfter != null) {
            v.add(new DERTaggedObject(false, 1, new DERGeneralizedTime(privateKeyNotAfter)));
        }
        certbuilder.addExtension(Extension.privateKeyUsagePeriod, false, new DERSequence(v));
    }

    // Subject and Authority key identifier is always non-critical and MUST be present for certificates to verify in Firefox.
    try {
        if (isCA) {

            ASN1InputStream sAsn1InputStream = new ASN1InputStream(
                    new ByteArrayInputStream(publicKey.getEncoded()));
            ASN1InputStream aAsn1InputStream = new ASN1InputStream(
                    new ByteArrayInputStream(publicKey.getEncoded()));
            try {
                SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo(
                        (ASN1Sequence) sAsn1InputStream.readObject());
                X509ExtensionUtils x509ExtensionUtils = new BcX509ExtensionUtils();
                SubjectKeyIdentifier ski = x509ExtensionUtils.createSubjectKeyIdentifier(spki);
                SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo(
                        (ASN1Sequence) aAsn1InputStream.readObject());
                AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki);

                certbuilder.addExtension(Extension.subjectKeyIdentifier, false, ski);
                certbuilder.addExtension(Extension.authorityKeyIdentifier, false, aki);
            } finally {
                sAsn1InputStream.close();
                aAsn1InputStream.close();
            }
        }
    } catch (IOException e) { // do nothing
    }

    // CertificatePolicies extension if supplied policy ID, always non-critical
    if (policyId != null) {
        PolicyInformation pi = new PolicyInformation(new ASN1ObjectIdentifier(policyId));
        DERSequence seq = new DERSequence(pi);
        certbuilder.addExtension(Extension.certificatePolicies, false, seq);
    }
    // Add any additional
    if (additionalExtensions != null) {
        for (final Extension extension : additionalExtensions) {
            certbuilder.addExtension(extension.getExtnId(), extension.isCritical(), extension.getParsedValue());
        }
    }
    final ContentSigner signer = new BufferingContentSigner(
            new JcaContentSignerBuilder(sigAlg).setProvider(provider).build(privKey), 20480);
    final X509CertificateHolder certHolder = certbuilder.build(signer);
    final X509Certificate selfcert = (X509Certificate) CertTools.getCertfromByteArray(certHolder.getEncoded());

    return selfcert;
}