Example usage for java.security KeyFactory generatePrivate

List of usage examples for java.security KeyFactory generatePrivate

Introduction

In this page you can find the example usage for java.security KeyFactory generatePrivate.

Prototype

public final PrivateKey generatePrivate(KeySpec keySpec) throws InvalidKeySpecException 

Source Link

Document

Generates a private key object from the provided key specification (key material).

Usage

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

public static byte[] getSignatureRS512(byte[] signingInput, RSAPrivateKey rsaPrivateKey)
        throws SignatureException, InvalidKeyException, NoSuchProviderException, InvalidKeySpecException,
        NoSuchAlgorithmException {
    RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec(rsaPrivateKey.getModulus(),
            rsaPrivateKey.getPrivateExponent());

    KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
    PrivateKey privateKey = keyFactory.generatePrivate(rsaPrivateKeySpec);

    Signature signature = Signature.getInstance("SHA512withRSA", "BC");
    signature.initSign(privateKey);//  ww  w  .  ja va 2 s.co  m
    signature.update(signingInput);

    return signature.sign();
}

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

public static byte[] getSignatureES256(byte[] signingInput, ECDSAPrivateKey ecdsaPrivateKey)
        throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException,
        SignatureException {/*from  ww w . j  a  va  2  s .  c om*/
    ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("P-256");
    ECPrivateKeySpec privateKeySpec = new ECPrivateKeySpec(ecdsaPrivateKey.getD(), ecSpec);

    KeyFactory keyFactory = KeyFactory.getInstance("ECDSA", "BC");
    PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);

    Signature signature = Signature.getInstance("SHA256WITHECDSA", "BC");
    signature.initSign(privateKey);
    signature.update(signingInput);

    return signature.sign();
}

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

public static byte[] getSignatureES384(byte[] signingInput, ECDSAPrivateKey ecdsaPrivateKey)
        throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException,
        SignatureException {// w w  w .ja  v  a  2  s  .  c  o m
    ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("P-384");
    ECPrivateKeySpec privateKeySpec = new ECPrivateKeySpec(ecdsaPrivateKey.getD(), ecSpec);

    KeyFactory keyFactory = KeyFactory.getInstance("ECDSA", "BC");
    PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);

    Signature signature = Signature.getInstance("SHA384WITHECDSA", "BC");
    signature.initSign(privateKey);
    signature.update(signingInput);

    return signature.sign();
}

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

public static byte[] getSignatureES512(byte[] signingInput, ECDSAPrivateKey ecdsaPrivateKey)
        throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException,
        SignatureException {//from  w ww . jav a2 s.  c o  m
    ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("P-521");
    ECPrivateKeySpec privateKeySpec = new ECPrivateKeySpec(ecdsaPrivateKey.getD(), ecSpec);

    KeyFactory keyFactory = KeyFactory.getInstance("ECDSA", "BC");
    PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);

    Signature signature = Signature.getInstance("SHA512WITHECDSA", "BC");
    signature.initSign(privateKey);
    signature.update(signingInput);

    return signature.sign();
}

From source file:com.vmware.identity.idm.server.ServerUtils.java

public static PrivateKey getPrivateKeyValue(LdapValue[] value) {
    PrivateKey privateKey = null;

    if ((value != null) && (value.length == 1)) {
        byte[] privateKeyBytes = value[0].getValue();
        if (privateKeyBytes != null) {
            try {
                KeyFactory keyFactory = KeyFactory.getInstance("RSA");

                EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);

                privateKey = keyFactory.generatePrivate(privateKeySpec);
            } catch (NoSuchAlgorithmException ex1) {
                throw new RuntimeException("No such algorithm");
            } catch (InvalidKeySpecException ex2) {
                throw new RuntimeException("Invalid key spec");
            }/*from w ww . ja v  a  2s  .  c  o  m*/
        }
    }
    return privateKey;
}

From source file:org.apache.camel.component.gae.auth.GAuthPk8Loader.java

/**
 * Loads a private key from a PKCS#8 file.
 *///from   ww w.  j  a v a 2 s  .c  o m
public PrivateKey loadPrivateKey() throws Exception {
    String str = IOUtils.toString(keyLocation.getInputStream());

    if (str.contains(BEGIN) && str.contains(END)) {
        str = str.substring(BEGIN.length(), str.lastIndexOf(END));
    }

    KeyFactory factory = KeyFactory.getInstance("RSA");
    return factory.generatePrivate(new PKCS8EncodedKeySpec(Base64.decode(str)));
}

From source file:org.jasig.cas.util.PrivateKeyFactoryBean.java

protected Object createInstance() throws Exception {
    final InputStream privKey = this.location.getInputStream();
    try {//from  w w w.  jav  a 2  s  .  com
        final byte[] bytes = new byte[privKey.available()];
        privKey.read(bytes);
        privKey.close();
        final PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(bytes);
        KeyFactory factory = KeyFactory.getInstance(this.algorithm);
        return factory.generatePrivate(privSpec);
    } finally {
        privKey.close();
    }
}

From source file:com.adeptj.modules.security.jwt.internal.JwtKeys.java

static PrivateKey createSigningKey(JwtConfig jwtConfig, SignatureAlgorithm signatureAlgo) {
    LOGGER.info("Creating RSA signing key!!");
    String keyData = jwtConfig.privateKey();
    Assert.isTrue(StringUtils.startsWithAny(keyData, PRIVATE_ENCRYPTED_KEY_HEADER, PRIVATE_KEY_HEADER),
            INVALID_PRIVATE_KEY_MSG);//w  w  w. j  a  v  a  2s. co m
    try {
        KeyFactory keyFactory = KeyFactory.getInstance(signatureAlgo.getFamilyName());
        if (StringUtils.startsWith(keyData, PRIVATE_ENCRYPTED_KEY_HEADER)) {
            LOGGER.info("Creating PKCS8EncodedKeySpec from private [encrypted] key !!");
            Assert.hasText(jwtConfig.privateKeyPassword(), KEYPASS_NULL_MSG);
            byte[] privateKeyData = decodePrivateKeyData(keyData, true);
            EncryptedPrivateKeyInfo privateKeyInfo = new EncryptedPrivateKeyInfo(privateKeyData);
            SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(privateKeyInfo.getAlgName());
            PBEKeySpec keySpec = new PBEKeySpec(jwtConfig.privateKeyPassword().toCharArray());
            SecretKey secretKey = secretKeyFactory.generateSecret(keySpec);
            Cipher cipher = Cipher.getInstance(privateKeyInfo.getAlgName());
            cipher.init(DECRYPT_MODE, secretKey, privateKeyInfo.getAlgParameters());
            return keyFactory.generatePrivate(privateKeyInfo.getKeySpec(cipher));
        }
        LOGGER.info("Creating PKCS8EncodedKeySpec from private key !!");
        return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(decodePrivateKeyData(keyData, false)));
    } catch (GeneralSecurityException | IOException ex) {
        LOGGER.error(ex.getMessage(), ex);
        throw new KeyInitializationException(ex.getMessage(), ex);
    }
}

From source file:com.microsoft.azure.keyvault.test.CertificateOperationsTest.java

/**
 * Extracts private key from PEM contents
 * /*from www.j  a  v  a 2s.  c o  m*/
 * @throws InvalidKeySpecException
 * @throws NoSuchAlgorithmException
 */
private static PrivateKey extractPrivateKeyFromPemContents(String pemContents)
        throws InvalidKeySpecException, NoSuchAlgorithmException {
    Matcher matcher = _privateKey.matcher(pemContents);
    if (!matcher.find()) {
        throw new IllegalArgumentException("No private key found in PEM contents.");
    }

    byte[] privateKeyBytes = _base64.decode(matcher.group(1));
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(ALGO_RSA);
    PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
    return privateKey;
}

From source file:hudson.model.UsageStatisticsTest.java

/**
 * Makes sure that the stat data can be decrypted safely.
 *//*from   w  w w  . j  ava  2s.  co  m*/
public void testRoundtrip() throws Exception {
    // key pair for testing
    String privateKey = "30820276020100300d06092a864886f70d0101010500048202603082025c0201000281810084cababdb38040f659c2cb07a36d758f46e84ebc3d6ba39d967aedf1d396b0788ed3ab868d45ce280b1102b434c2a250ddc3254defe1785ab4f94d7038cf69ecca16753d2de3f6ad8976b3f74902d8634111d730982da74e1a6e3fc0bc3523bba53e45b8a8cbfd0321b94efc9f7fefbe66ad85281e3d0323d87f4426ec51204f0203010001028180784deaacdea8bd31f2d44578601954be3f714b93c2d977dbd76efb8f71303e249ad12dbeb2d2a1192a1d7923a6010768d7e06a3597b3df83de1d5688eb0f0e58c76070eddd696682730c93890dc727564c65dc8416bfbde5aad4eb7a97ed923efb55a291daf3c00810c0e43851298472fd539aab355af8cedcf1e9a0cbead661024100c498375102b068806c71dec838dc8dfa5624fb8a524a49cffadc19d10689a8c9c26db514faba6f96e50a605122abd3c9af16e82f2b7565f384528c9f31ea5947024100aceafd31d7f4872a873c7e5fe88f20c2fb086a053c6970026b3ce364768e2033100efb1ad8f2010fe53454a29decedc23a8a0c8df347742b1f13e11bd3a284b9024100931321470cd0f6cd24d4278bf8e61f9d69b6ef2bf3163a944aa340f91c7ffdf33aeea22b18cc43514af6714a21bb148d6cdca14530a8fa65acd7a8f62bfc9b5f024067452059f8438dc61466488336fce3f00ec483ad04db638dce45daf850e5a8cd5635dc39b87f2fab32940247ec5167ddabe06e870858104500967ac687aa73e102407e3b7997503e18d8d0f094d5e0bd5d57cb93cb39a2fc42cec1ea9a1562786438b61139e45813204d72c919f5397e139ad051d98e4d0f8a06d237f42c0d8440fb";
    String publicKey = "30819f300d06092a864886f70d010101050003818d003081890281810084cababdb38040f659c2cb07a36d758f46e84ebc3d6ba39d967aedf1d396b0788ed3ab868d45ce280b1102b434c2a250ddc3254defe1785ab4f94d7038cf69ecca16753d2de3f6ad8976b3f74902d8634111d730982da74e1a6e3fc0bc3523bba53e45b8a8cbfd0321b94efc9f7fefbe66ad85281e3d0323d87f4426ec51204f0203010001";

    String data = new UsageStatistics(publicKey).getStatData();
    System.out.println(data);

    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PrivateKey priv = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(Util.fromHexString(privateKey)));

    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.DECRYPT_MODE, priv);

    byte[] cipherText = Base64.decode(data.toCharArray());
    InputStreamReader r = new InputStreamReader(
            new GZIPInputStream(
                    new CombinedCipherInputStream(new ByteArrayInputStream(cipherText), cipher, "AES", 1024)),
            "UTF-8");
    JSONObject o = JSONObject.fromObject(IOUtils.toString(r));
    System.out.println(o);
    assertEquals(1, o.getInt("stat"));
}