Example usage for java.security KeyFactory getInstance

List of usage examples for java.security KeyFactory getInstance

Introduction

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

Prototype

public static KeyFactory getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a KeyFactory object that converts public/private keys of the specified algorithm.

Usage

From source file:org.wso2.sample.identity.oauth2.IDTokenDecrypterServlet.java

/**
 * Decrypt the id token using the private key.
 *
 * @param JWE              id token to be decrypted
 * @param privateKeyString client private key as a string
 * @return decrypted id token as an EncryptedJWT object
 * @throws NoSuchAlgorithmException/*from w w w .jav  a 2 s. co  m*/
 * @throws InvalidKeySpecException
 * @throws ParseException
 * @throws JOSEException
 * @throws IllegalArgumentException
 */
private EncryptedJWT decryptJWE(String JWE, String privateKeyString) throws NoSuchAlgorithmException,
        InvalidKeySpecException, ParseException, JOSEException, IllegalArgumentException {

    KeyFactory kf = KeyFactory.getInstance("RSA");
    // Remove EOF characters from key string and generate key object.
    privateKeyString = privateKeyString.replace("\n", "").replace("\r", "");
    PKCS8EncodedKeySpec keySpecPKCS8 = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKeyString));
    PrivateKey privateKey = kf.generatePrivate(keySpecPKCS8);

    EncryptedJWT jwt = EncryptedJWT.parse(JWE);

    // Create a decrypter with the specified private RSA key.
    RSADecrypter decrypter = new RSADecrypter((RSAPrivateKey) privateKey);

    jwt.decrypt(decrypter);

    return jwt;
}

From source file:com.znsx.util.licence.LicenceUtil.java

/**
 * ?????/*  w ww.  j a va2  s .co m*/
 * 
 * @param data
 *            ??
 * @param privateKey
 *            ???base64?
 * @return base64????
 * @throws Exception
 */
public static String sign(String data, String privateKeyString) throws Exception {
    Base64 base64 = new Base64();
    // ????
    // BASE64Decoder decoder = new BASE64Decoder();
    // byte[] bytes = decoder.decodeBuffer(privateKeyString);
    byte[] bytes = base64.decode(privateKeyString.getBytes("utf8"));
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes);
    PrivateKey privateKey = KeyFactory.getInstance("DSA").generatePrivate(keySpec);
    // ???
    Signature signature = Signature.getInstance("DSA");
    signature.initSign(privateKey);
    signature.update(data.getBytes("utf8"));
    // return new BASE64Encoder().encode(signature.sign());
    return new String(base64.encode(signature.sign()), "utf8");
}

From source file:be.fedict.eid.idp.model.CryptoUtil.java

public static PublicKey getPublicKey(byte[] publicKeyBytes) throws KeyLoadException {

    try {//from  www .j  a v a2 s  . c  o m
        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes);
        KeyFactory rsaKeyFactory = KeyFactory.getInstance("RSA");
        return rsaKeyFactory.generatePublic(publicKeySpec);

    } catch (InvalidKeySpecException e) {
        throw new KeyLoadException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.vmware.identity.rest.idm.data.PrivateKeyDTO.java

private static PrivateKey decodePrivateKey(String encoded, String algorithm)
        throws InvalidKeySpecException, NoSuchAlgorithmException {
    if (encoded == null) {
        return null;
    }/*w w  w . j  a v  a2  s .  co m*/

    byte[] clear = Base64.decodeBase64(encoded);
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(clear);
    KeyFactory fact = KeyFactory.getInstance(algorithm);
    PrivateKey privateKey = fact.generatePrivate(keySpec);
    Arrays.fill(clear, (byte) 0);
    return privateKey;
}

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

static PublicKey createVerificationKey(SignatureAlgorithm signatureAlgo, String publicKey) {
    LOGGER.info("Creating RSA verification key!!");
    Assert.isTrue(StringUtils.startsWith(publicKey, PUB_KEY_HEADER), INVALID_PUBLIC_KEY_MSG);
    try {/*from ww w  .  ja v  a  2  s .c o  m*/
        KeyFactory keyFactory = KeyFactory.getInstance(signatureAlgo.getFamilyName());
        byte[] publicKeyData = Base64.getDecoder().decode(publicKey.replace(PUB_KEY_HEADER, EMPTY)
                .replace(PUB_KEY_FOOTER, EMPTY).replaceAll(REGEX_SPACE, EMPTY).trim().getBytes(UTF_8));
        LOGGER.info("Creating X509EncodedKeySpec from public key !!");
        return keyFactory.generatePublic(new X509EncodedKeySpec(publicKeyData));
    } catch (GeneralSecurityException ex) {
        LOGGER.error(ex.getMessage(), ex);
        throw new KeyInitializationException(ex.getMessage(), ex);
    }
}

From source file:gemlite.core.util.RSAUtils.java

/**
 * <p>/*from   ww  w  .j  ava2s. c  o  m*/
 * ??
 * </p>
 * 
 * @param data
 *          ?
 * @param publicKey
 *          (BASE64?)
 * @param sign
 *          ??
 * 
 * @return
 * @throws Exception
 * 
 */
public static boolean verify(byte[] data, String publicKey, String sign) throws Exception {
    byte[] keyBytes = Base64Utils.decode(publicKey);
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    PublicKey publicK = keyFactory.generatePublic(keySpec);
    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
    signature.initVerify(publicK);
    signature.update(data);
    return signature.verify(Base64Utils.decode(sign));
}

From source file:com.dreamworks.dsp.server.EmbeddedSftpServer.java

private PublicKey decodePublicKey() throws Exception {
    InputStream stream = new ClassPathResource("keys/sftp_rsa.pub").getInputStream();
    byte[] decodeBuffer = Base64.decodeBase64(StreamUtils.copyToByteArray(stream));
    ByteBuffer bb = ByteBuffer.wrap(decodeBuffer);
    int len = bb.getInt();
    byte[] type = new byte[len];
    bb.get(type);//from www  .java2  s.co  m
    if ("ssh-rsa".equals(new String(type))) {
        BigInteger e = decodeBigInt(bb);
        BigInteger m = decodeBigInt(bb);
        RSAPublicKeySpec spec = new RSAPublicKeySpec(m, e);
        return KeyFactory.getInstance("RSA").generatePublic(spec);

    } else {
        throw new IllegalArgumentException("Only supports RSA");
    }
}

From source file:bftsmart.reconfiguration.util.RSAKeyLoaderO.java

private PublicKey getPublicKeyFromString(String key) throws Exception {

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

    EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(Base64.decodeBase64(key));

    PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

    return publicKey;

}

From source file:net.padlocksoftware.padlock.KeyManager.java

/**
 * Import a Padlock 2.x (DSA based) KeyPair from an InputStream.  The stream is
 * assumed to have been previously exported in a supported format using the
 * exportKeyPair methods./*from  w w w  . j ava2 s  .c  o m*/
 * @param stream The KeyPair stream to import.
 * @return The DSA KeyPair contained in the specified file.
 * @throws java.io.IOException If file is missing or contain invalid data.
 * @since 2.0
 */
public static KeyPair importKeyPair(InputStream stream) throws IOException {
    if (stream == null)
        throw new IllegalArgumentException("Stream cannot be null");

    KeyPair pair = null;
    Properties p = new Properties();
    p.load(stream);
    stream.close();
    String pri = p.getProperty("private");
    String pub = p.getProperty("public");

    if (pri == null || pub == null) {
        throw new IOException("Stream data is invalid");
    }

    // Load the keys
    try {

        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(Hex.decodeHex(pri.toCharArray()));
        KeyFactory keyFactory = KeyFactory.getInstance("DSA");
        PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);

        X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(Hex.decodeHex(pub.toCharArray()));
        PublicKey publicKey = keyFactory.generatePublic(pubSpec);

        pair = new KeyPair(publicKey, privateKey);
    } catch (Exception e) {
        throw new RuntimeException("Invalid stream: " + e.getMessage());
    }

    return pair;
}

From source file:com.aqnote.shared.cryptology.asymmetric.DSA.java

/**
 * ?private key// ww  w. j  a v  a2s  .  c  o  m
 * 
 * @throws RuntimeException key
 */
public static PrivateKey readPrivateKey(byte[] keyBytes) throws RuntimeException {
    try {
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
        byte[] encodedKey = Base64.decodeBase64(keyBytes);
        EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encodedKey);
        return keyFactory.generatePrivate(keySpec);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (InvalidKeySpecException e) {
        e.printStackTrace();
    }
    return null;
}