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:com.microsoft.azure.oidc.token.impl.SimpleTokenValidator.java

@Override
public Boolean validateSignature(final Token token) {
    if (token == null) {
        throw new PreconditionException("Required parameter is null");
    }/*w ww .j av  a 2 s  .  c o  m*/
    if (algorithmConfigurationService.get().getAlgorithmClassMap().get(token.getAlgorithm().getName())
            .equals("HMAC")) {
        return Boolean.FALSE;
    }
    final Configuration configuration = configurationCache.load();
    if (configuration == null) {
        throw new GeneralException("Error loading configuration");
    }
    try {
        final TimeStamp now = timeStampFactory.createTimeStamp(System.currentTimeMillis() / 1000);
        if (configuration.getKey(token.getKeyName()).getNotBefore().compareTo(now) > 0) {
            return Boolean.FALSE;
        }
        final Base64 decoder = new Base64();
        final BigInteger exponent = new BigInteger(1,
                decoder.decode(configuration.getKey(token.getKeyName()).getExponent().getValue()));
        final BigInteger modulus = new BigInteger(1,
                decoder.decode(configuration.getKey(token.getKeyName()).getSecret().getValue()));
        final RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(modulus, exponent);
        final KeyFactory keyFactory = KeyFactory.getInstance(
                algorithmConfigurationService.get().getAlgorithmClassMap().get(token.getAlgorithm().getName()));
        final PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);
        final Signature sig = Signature.getInstance(
                algorithmConfigurationService.get().getAlgorithmMap().get(token.getAlgorithm().getName()));
        sig.initVerify(pubKey);
        sig.update(token.getPayload().getValue().getBytes());
        return sig.verify(decoder.decode(token.getSignature().getValue()));
    } catch (NoSuchAlgorithmException | InvalidKeySpecException | SignatureException | InvalidKeyException e) {
        LOGGER.error(e.getMessage(), e);
        return Boolean.FALSE;
    }
}

From source file:org.xdi.oxauth.model.jws.RSASigner.java

@Override
public boolean validateSignature(String signingInput, String signature) throws SignatureException {
    if (getSignatureAlgorithm() == null) {
        throw new SignatureException("The signature algorithm is null");
    }// w  w  w  .java  2 s . c om
    if (rsaPublicKey == null) {
        throw new SignatureException("The RSA public key is null");
    }
    if (signingInput == null) {
        throw new SignatureException("The signing input is null");
    }

    String algorithm = null;
    switch (getSignatureAlgorithm()) {
    case RS256:
        algorithm = "SHA-256";
        break;
    case RS384:
        algorithm = "SHA-384";
        break;
    case RS512:
        algorithm = "SHA-512";
        break;
    default:
        throw new SignatureException("Unsupported signature algorithm");
    }

    ASN1InputStream aIn = null;
    try {
        byte[] sigBytes = JwtUtil.base64urldecode(signature);
        byte[] sigInBytes = signingInput.getBytes(Util.UTF8_STRING_ENCODING);

        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);
        aIn = new ASN1InputStream(decSig);

        ASN1Sequence seq = (ASN1Sequence) aIn.readObject();

        MessageDigest hash = MessageDigest.getInstance(algorithm, "BC");
        hash.update(sigInBytes);

        ASN1OctetString sigHash = (ASN1OctetString) seq.getObjectAt(1);
        return MessageDigest.isEqual(hash.digest(), sigHash.getOctets());
    } catch (IOException e) {
        throw new SignatureException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new SignatureException(e);
    } catch (InvalidKeyException e) {
        throw new SignatureException(e);
    } catch (InvalidKeySpecException e) {
        throw new SignatureException(e);
    } catch (NoSuchPaddingException e) {
        throw new SignatureException(e);
    } catch (BadPaddingException e) {
        throw new SignatureException(e);
    } catch (NoSuchProviderException e) {
        throw new SignatureException(e);
    } catch (IllegalBlockSizeException e) {
        throw new SignatureException(e);
    } catch (Exception e) {
        throw new SignatureException(e);
    } finally {
        IOUtils.closeQuietly(aIn);
    }
}

From source file:io.kodokojo.config.module.SecurityModule.java

@Provides
@Singleton/* w  ww . j a v a2 s  .  c o m*/
SSLKeyPair provideSSLKeyPair(SecurityConfig securityConfig) {
    if (securityConfig == null) {
        throw new IllegalArgumentException("securityConfig must be defined.");
    }
    if (StringUtils.isNotBlank(securityConfig.wildcardPemPath())) {

        File pemFile = new File(securityConfig.wildcardPemPath());
        try {
            String content = IOUtils.toString(new FileReader(pemFile));
            String contentPrivate = RSAUtils.extractPrivateKey(content);
            String contentPublic = RSAUtils.extractPublic(content);

            RSAPrivateKey rsaPrivateKey = RSAUtils.readRsaPrivateKey(new StringReader(contentPrivate));
            X509Certificate certificate = RSAUtils.readRsaPublicKey(new StringReader(contentPublic));
            RSAPublicKey rsaPublicKey = (RSAPublicKey) certificate.getPublicKey();

            X509Certificate[] certificates = new X509Certificate[1];
            certificates[0] = certificate;
            LOGGER.info(
                    "Using Wildcard SSL certificat {} from path {}to provide Certificat to all instances of Kodo Kojo. ",
                    certificate.getSubjectDN().toString(), securityConfig.wildcardPemPath());
            return new SSLKeyPair(rsaPrivateKey, rsaPublicKey, certificates);
        } catch (IOException e) {
            throw new IllegalArgumentException("Unable to read pem file " + pemFile.getAbsolutePath() + ".", e);
        }
    } else {
        try {
            KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
            ks.load(new FileInputStream(System.getProperty("javax.net.ssl.keyStore")),
                    System.getProperty("javax.net.ssl.keyStorePassword", "").toCharArray());

            RSAPrivateCrtKey key = (RSAPrivateCrtKey) ks.getKey(securityConfig.sslRootCaKsAlias(),
                    securityConfig.sslRootCaKsPassword().toCharArray());
            if (key == null) {
                return null;
            }

            RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(key.getModulus(), key.getPublicExponent());

            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(publicKeySpec);
            Certificate[] certificateChain = ks.getCertificateChain(securityConfig.sslRootCaKsAlias());
            List<X509Certificate> x509Certificates = Arrays.asList(certificateChain).stream()
                    .map(c -> (X509Certificate) c).collect(Collectors.toList());
            LOGGER.info(
                    "Using a CA SSL certificat {} from keystore  to provide Certificat to all instances of Kodo Kojo. ",
                    securityConfig.sslRootCaKsAlias(), System.getProperty("javax.net.ssl.keyStore"));
            return new SSLKeyPair(key, publicKey,
                    x509Certificates.toArray(new X509Certificate[x509Certificates.size()]));
        } catch (UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException
                | InvalidKeySpecException | CertificateException | IOException e) {

            throw new RuntimeException("Unable to open default Keystore", e);
        }
    }
}

From source file:license.regist.ReadProjectInfo.java

static PublicKey readPublicKeyFromFile() throws Exception {
    ObjectInputStream oin = new ObjectInputStream(new ByteArrayInputStream(KeyData.publicKey));
    try {/*from w w w  . ja v a 2s. c  o  m*/
        BigInteger m = (BigInteger) oin.readObject();
        BigInteger e = (BigInteger) oin.readObject();
        RSAPublicKeySpec keySpec = new RSAPublicKeySpec(m, e);
        KeyFactory fact = KeyFactory.getInstance("RSA");
        return fact.generatePublic(keySpec);
    } finally {
        oin.close();
    }
}

From source file:org.mitre.jwt.JwtTest.java

/**
 * @throws Exception//from ww  w . j a va2  s  .c  o  m
 */
@Test
public void testGenerateRsaSignature() throws Exception {

    // Hard code the private/public key so as not to depend on it being in
    // the keystore...

    RSAPrivateKeySpec privateSpec = new RSAPrivateKeySpec(new BigInteger(
            "AD6E684550542947AD95EF9BACDC0AC2C9168C6EB3212D378C23E5539266111DB2E5B4D42B1E47EB4F7A65DB63D9782C72BC365492FD1E5C7B4CD2174C611668C29013FEDE22619B3F58DA3531BB6C02B3266768B7895CBDAFB3F9AC7A7B2F3DB17EF4DCF03BD2575604BDE0A01BB1FB7B0E733AD63E464DB4D7D89626297A214D7CECCD0C50421A322A01E9DCEA23443F6A9339576B31DFA504A133076394562CB57F3FDEDB26F9A82BED2F6D52D6F6BF8286E2497EF0B5C8456F32B4668F5A9F5FCD3781345DDDB749792C37238A53D18FD976C0C9D1F1E211F1A4A9AAE679C45B92D1741EF0D3C3F373232CE7FB93E9BC461E1C508A20B74E7E3361B3C527",
            16),
            new BigInteger(
                    "627CDD67E75B33EA0990A8F64DEED389942A62EB867C23B274B9F9C440D2078C47089D6D136369D21E5B52B688F8797F3C54D7C1A58B6A8F7851C2C90A4DE42CEFB864328B31191ED19582AD4CA5B38BC0F2E12C9D75BB1DD946AA55A1648D0A4ADEDEED0CDBDBF24EDDF87A345225FBBB0114BCE7E78B831B5CAC197068837AB0B3F07157952A05F67A72B9852972C704B6B32A70C3BB3DEB186936B0F7D6ABE012DEB89BC2DBE1F88AE7A28C06C53D1FB2459E58D8ED266E3BFC28266981D2A5F624D36555DD64F410461ADA5D53F448BA5EEBBD4BCEC3AF53285FB394650D7B3BFB06712E081AAD160EED6E83A3EA2D092712C07A6331209F62D27184BFC9",
                    16));

    KeyFactory keyFactory = KeyFactory.getInstance("RSA");

    PrivateKey privateKey = keyFactory.generatePrivate(privateSpec);

    RSAPublicKeySpec publicSpec = new RSAPublicKeySpec(new BigInteger(
            "AD6E684550542947AD95EF9BACDC0AC2C9168C6EB3212D378C23E5539266111DB2E5B4D42B1E47EB4F7A65DB63D9782C72BC365492FD1E5C7B4CD2174C611668C29013FEDE22619B3F58DA3531BB6C02B3266768B7895CBDAFB3F9AC7A7B2F3DB17EF4DCF03BD2575604BDE0A01BB1FB7B0E733AD63E464DB4D7D89626297A214D7CECCD0C50421A322A01E9DCEA23443F6A9339576B31DFA504A133076394562CB57F3FDEDB26F9A82BED2F6D52D6F6BF8286E2497EF0B5C8456F32B4668F5A9F5FCD3781345DDDB749792C37238A53D18FD976C0C9D1F1E211F1A4A9AAE679C45B92D1741EF0D3C3F373232CE7FB93E9BC461E1C508A20B74E7E3361B3C527",
            16), new BigInteger("10001", 16));

    PublicKey publicKey = keyFactory.generatePublic(publicSpec);

    Jwt jwt = new Jwt();
    jwt.getHeader().setType("JWT");
    jwt.getHeader().setAlgorithm("RS256");
    jwt.getClaims().setExpiration(new Date(1300819380L * 1000L));
    jwt.getClaims().setIssuer("joe");
    jwt.getClaims().setClaim("http://example.com/is_root", Boolean.TRUE);

    JwtSigner signer = new RsaSigner(JwsAlgorithm.RS256.getJwaName(), publicKey, privateKey);
    ((RsaSigner) signer).afterPropertiesSet();

    /*
     * Expected string based on the following structures, serialized exactly
     * as follows and base64 encoded:
     * 
     * header: {"typ":"JWT","alg":"HS256"} claims:
     * {"exp":1300819380,"iss":"joe","http://example.com/is_root":true}
     * 
     * Expected signature: dSRvtD-ExzGN-
     * fRXd1wRZOPo1JFPuqgwvaIKp8jgcyMXJegy6IUjssfUfUcICN5yvh0ggOMWMeWkwQ7
     * -PlXMJWymdhXVI3BOpNt7ZOB2vMFYSOOHNBJUunQoe1lmNxuHQdhxqoHahn3u1cLDXz
     * -xx-
     * JELduuMmaDWqnTFPodVPl45WBKHaQhlOiFWj3ZClUV2k5p2yBT8TmxekL8gWwgVbQk5yPnYOs
     * -PcMjzODc9MZX4yI10ZSCSDciwf-
     * rgkQLT7wW4uZCoqTZ7187sCodHd6nw3nghqbtqN05fQ3Yq7ykwaR8pdQBFb2L9l7DhLLuXIREDKIFUHBSUs8OnvXFMg
     */

    String signature = "dSRvtD-ExzGN-fRXd1wRZOPo1JFPuqgwvaIKp8jgcyMXJegy6IUjssfUfUcICN5yvh0ggOMWMeWkwQ7-PlXMJWymdhXVI3BOpNt7ZOB2vMFYSOOHNBJUunQoe1lmNxuHQdhxqoHahn3u1cLDXz-xx-JELduuMmaDWqnTFPodVPl45WBKHaQhlOiFWj3ZClUV2k5p2yBT8TmxekL8gWwgVbQk5yPnYOs-PcMjzODc9MZX4yI10ZSCSDciwf-rgkQLT7wW4uZCoqTZ7187sCodHd6nw3nghqbtqN05fQ3Yq7ykwaR8pdQBFb2L9l7DhLLuXIREDKIFUHBSUs8OnvXFMg";
    String expected = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJleHAiOjEzMDA4MTkzODAsImlzcyI6ImpvZSIsImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ"
            + "." + signature;

    signer.sign(jwt);

    String actual = jwt.toString();

    assertThat(signer.verify(actual), equalTo(true));
    assertThat(actual, equalTo(expected));
    assertThat(jwt.getSignature(), equalTo(signature));
}

From source file:com.cellngine.crypto.RSACipher.java

@Override
public void loadPublicKey(final byte[] fromBytes) {
    final BigInteger[] keyData = this.getKeyData(fromBytes);
    final RSAPublicKeySpec spec = new RSAPublicKeySpec(keyData[0], keyData[1]);
    this.publicKey = this.getPublicKey(spec);
}

From source file:eu.dety.burp.joseph.utilities.Converter.java

/**
 * Build RSA {@link PublicKey} from RSA JWK JSON object
 * /*  ww  w. ja  va  2  s.c  om*/
 * @param input
 *            RSA JSON Web Key {@link JSONObject}
 * @return {@link PublicKey} or null
 */
private static PublicKey buildRsaPublicKeyByJwk(JSONObject input) {
    try {
        BigInteger modulus = new BigInteger(Base64.decodeBase64(input.get("n").toString()));
        BigInteger publicExponent = new BigInteger(Base64.decodeBase64(input.get("e").toString()));

        loggerInstance.log(Converter.class, "RSA PublicKey values: N: " + modulus + " E: " + publicExponent,
                Logger.LogLevel.DEBUG);
        return KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(modulus, publicExponent));
    } catch (Exception e) {
        return null;
    }
}

From source file:de.pawlidi.openaletheia.generator.KeyGenerator.java

public static RSAPublicKeySpec readPublicKeySpec(final String directory) {
    if (StringUtils.isBlank(directory) || !new File(directory).isDirectory()) {
        return null;
    }/* w  ww.  j a  va 2s . c  o m*/
    RSAPublicKeySpec publicKeySpec = null;
    ObjectInputStream inputStream = null;
    try {
        inputStream = new ObjectInputStream(
                new BufferedInputStream(new FileInputStream(new File(directory, PUBLIC_KEYSPEC_FILE))));
        try {
            BigInteger m = (BigInteger) inputStream.readObject();
            BigInteger e = (BigInteger) inputStream.readObject();
            publicKeySpec = new RSAPublicKeySpec(m, e);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                inputStream.close();
                inputStream = null;
            }
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return publicKeySpec;
}

From source file:org.excalibur.core.util.SecurityUtils2.java

public static PublicKey readPublicKey(byte[] bytes) throws GeneralSecurityException, IOException {
    // http://stackoverflow.com/questions/12749858
    // http://tools.ietf.org/html/rfc4716
    // http://tools.ietf.org/html/rfc4251
    try (DataInputStream in = new DataInputStream(new ByteArrayInputStream(bytes))) {
        byte[] sshRsa = new byte[in.readInt()];
        in.readFully(sshRsa);//  w  ww . j a  v  a  2  s .co m

        byte[] exp = new byte[in.readInt()];
        in.readFully(exp);

        byte[] mod = new byte[in.readInt()];
        in.readFully(mod);

        RSAPublicKeySpec spec = new RSAPublicKeySpec(new BigInteger(mod), new BigInteger(exp));
        return SecurityUtils.getKeyFactory("RSA").generatePublic(spec);
    }
}

From source file:jenkins.bouncycastle.api.PEMEncodable.java

/**
 * Creates a {@link PEMEncodable} by decoding PEM formated data from a {@link String}
 * //from w  w  w.j  a  v  a  2  s. c o  m
 * @param pem {@link String} with the PEM data
 * @param passphrase passphrase for the encrypted PEM data. null if PEM data is not passphrase protected. The caller
 * is responsible for zeroing out the char[] after use to ensure the password does not stay in memory, e.g. with
 * <code>Arrays.fill(passphrase, (char)0)</code>
 * @return {@link PEMEncodable} object
 * @throws IOException launched if a problem exists reading the PEM information
 * @throws UnrecoverableKeyException in case PEM is passphrase protected and none or wrong is provided
 */
@Nonnull
public static PEMEncodable decode(@Nonnull String pem, @Nullable final char[] passphrase)
        throws IOException, UnrecoverableKeyException {

    try (PEMParser parser = new PEMParser(new StringReader(pem));) {

        Object object = parser.readObject();

        JcaPEMKeyConverter kConv = new JcaPEMKeyConverter().setProvider("BC");

        // handle supported PEM formats.
        if (object instanceof PEMEncryptedKeyPair) {
            if (passphrase != null) {
                PEMDecryptorProvider dp = new JcePEMDecryptorProviderBuilder().build(passphrase);
                PEMEncryptedKeyPair ekp = (PEMEncryptedKeyPair) object;
                return new PEMEncodable(kConv.getKeyPair(ekp.decryptKeyPair(dp)));
            } else {
                throw new UnrecoverableKeyException();
            }
        } else if (object instanceof PKCS8EncryptedPrivateKeyInfo) {
            if (passphrase != null) {
                InputDecryptorProvider dp = new JceOpenSSLPKCS8DecryptorProviderBuilder().build(passphrase);
                PKCS8EncryptedPrivateKeyInfo epk = (PKCS8EncryptedPrivateKeyInfo) object;
                return new PEMEncodable(kConv.getPrivateKey(epk.decryptPrivateKeyInfo(dp)));
            } else {
                throw new UnrecoverableKeyException();
            }
        } else if (object instanceof PEMKeyPair) {
            return new PEMEncodable(kConv.getKeyPair((PEMKeyPair) object));
        } else if (object instanceof PrivateKeyInfo) {
            PrivateKey pk = kConv.getPrivateKey((PrivateKeyInfo) object);

            // JENKINS-35661 in this case we know how to get the public key too
            if (pk instanceof RSAPrivateCrtKey) {
                // obtain public key spec from the private key
                RSAPrivateCrtKey rsaPK = (RSAPrivateCrtKey) pk;
                RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(rsaPK.getModulus(),
                        rsaPK.getPublicExponent());
                KeyFactory kf = KeyFactory.getInstance("RSA");
                return new PEMEncodable(new KeyPair(kf.generatePublic(pubKeySpec), rsaPK));
            }

            return new PEMEncodable(pk);
        } else if (object instanceof SubjectPublicKeyInfo) {
            return new PEMEncodable(kConv.getPublicKey((SubjectPublicKeyInfo) object));
        } else if (object instanceof X509CertificateHolder) {
            JcaX509CertificateConverter cConv = new JcaX509CertificateConverter().setProvider("BC");
            return new PEMEncodable(cConv.getCertificate((X509CertificateHolder) object));
        } else {
            throw new IOException(
                    "Could not parse PEM, only key pairs, private keys, public keys and certificates are supported. Received "
                            + object.getClass().getName());
        }
    } catch (OperatorCreationException e) {
        throw new IOException(e.getMessage(), e);
    } catch (PKCSException | InvalidKeySpecException e) {
        LOGGER.log(Level.WARNING, "Could not read PEM encrypted information", e);
        throw new UnrecoverableKeyException();
    } catch (CertificateException e) {
        throw new IOException("Could not read certificate", e);
    } catch (NoSuchAlgorithmException e) {
        throw new AssertionError(
                "RSA algorithm support is mandated by Java Language Specification. See https://docs.oracle.com/javase/7/docs/api/java/security/KeyFactory.html");
    }
}