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:eu.dety.burp.joseph.utilities.Converter.java

/**
 * Build {@link RSAPublicKey} from PublicKey PEM string
 * //from w  w  w  .  jav a 2 s. com
 * @param pemInput
 *            PublicKey PEM string
 * @return {@link RSAPublicKey} or null
 */
public static RSAPublicKey getRsaPublicKeyByPemString(String pemInput) {
    RSAPublicKey publicKey = null;

    String pubKey = pemInput.replaceAll("(-+BEGIN PUBLIC KEY-+\\r?\\n|-+END PUBLIC KEY-+\\r?\\n?)", "");

    // PKCS8
    try {
        byte[] keyBytes = Base64.decodeBase64(pubKey);

        X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        publicKey = (RSAPublicKey) keyFactory.generatePublic(spec);
    } catch (Exception e) {
    }

    // PKCS1
    try {
        byte[] keyBytes = Base64.decodeBase64(pubKey);
        keyBytes = Arrays.copyOfRange(keyBytes, 24, keyBytes.length);

        X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        publicKey = (RSAPublicKey) keyFactory.generatePublic(spec);
    } catch (Exception e) {
    }

    return publicKey;
}

From source file:com.zxy.commons.codec.rsa.RSAUtils.java

/**
 * <p>/*from w w  w  . j  ava  2 s.  c o  m*/
 * 
 * </p>
 * 
 * @param data ??
 * @param publicKey (BASE64?)
 * @return byte
 * @throws Exception Exception
 */
public static byte[] encryptByPublicKey(byte[] data, String publicKey) throws Exception {
    byte[] keyBytes = Base64.decodeBase64(publicKey);
    X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    Key publicK = keyFactory.generatePublic(x509KeySpec);
    // ?
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.ENCRYPT_MODE, publicK);
    int inputLen = data.length;
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    int offSet = 0;
    byte[] cache;
    int index = 0;
    // ?
    while (inputLen - offSet > 0) {
        if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
            cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
        } else {
            cache = cipher.doFinal(data, offSet, inputLen - offSet);
        }
        out.write(cache, 0, cache.length);
        index++;
        offSet = index * MAX_ENCRYPT_BLOCK;
    }
    byte[] encryptedData = out.toByteArray();
    out.close();
    return encryptedData;
}

From source file:com.ibm.mqlight.api.security.KeyStoreUtils.java

/**
 * Creates a {@link PrivateKey} instance from the passed private key PEM format file and certificate chain.
 *
 * @param pemKeyFile//from  w  w  w .  j a  v a  2  s.  co m
 *            A PEM format file containing the private key.
 * @param passwordChars
 *            The password that protects the private key.
 * @return the private key, created by this method.
 * @throws IOException if the file cannot be read.
 * @throws GeneralSecurityException if a cryptography problem is encountered.
 */
public static PrivateKey createPrivateKey(File pemKeyFile, char[] passwordChars)
        throws IOException, GeneralSecurityException {
    final String methodName = "createPrivateKey";
    logger.entry(methodName, pemKeyFile);

    // Read the private key from the PEM format file
    final PemFile privateKeyPemFile = new PemFile(pemKeyFile);
    final byte[] privateKeyBytes = privateKeyPemFile.getPrivateKeyBytes();

    final PrivateKey privateKey;
    if (privateKeyPemFile.containsEncryptedPrivateKey()) {
        // We should be able to do the follows (using standard JDK classes):
        //    EncryptedPrivateKeyInfo encryptPrivateKeyInfo = new EncryptedPrivateKeyInfo(privateKeyBytes);
        //    Cipher cipher = Cipher.getInstance(encryptPrivateKeyInfo.getAlgName());
        //    PBEKeySpec pbeKeySpec = new PBEKeySpec(passwordChars);
        //    SecretKeyFactory secFac = SecretKeyFactory.getInstance(encryptPrivateKeyInfo.getAlgName());
        //    Key pbeKey = secFac.generateSecret(pbeKeySpec);
        //    AlgorithmParameters algParams = encryptPrivateKeyInfo.getAlgParameters();
        //    cipher.init(Cipher.DECRYPT_MODE, pbeKey, algParams);
        //    KeySpec keySpec = encryptPrivateKeyInfo.getKeySpec(cipher);
        //    privateKey = KeyFactory.getInstance("RSA").generatePrivate(keySpec);
        // but this can fail with a: "Unsupported key protection algorithm" if key was generated with openssl
        //
        // Instead we use the Apache commons SSL PKCS8Key class from Julius Davies (see not-yet-commons-ssl in Maven)
        // which seems more reliable
        final PKCS8Key key = new PKCS8Key(privateKeyBytes, passwordChars);
        privateKey = key.getPrivateKey();
    } else {
        final KeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
        InvalidKeySpecException keyFactoryException = null;
        PrivateKey key = null;
        for (String alg : new String[] { "RSA", "DSA", "DiffieHellman", "EC" }) {
            try {
                key = KeyFactory.getInstance(alg).generatePrivate(keySpec);
                break;
            } catch (InvalidKeySpecException e) {
                if (keyFactoryException == null)
                    keyFactoryException = e;
            }
        }
        if (key == null)
            throw keyFactoryException;
        privateKey = key;
    }

    logger.exit(methodName, privateKey);

    return privateKey;
}

From source file:license.TestWakeLicense.java

/**
 * ??//from   w w  w. j av a2s .c om
 * @return
 * @throws Exception
 */
private static PrivateKey readPrivateKeyFromFile() throws Exception {
    //??
    ObjectInputStream oin = new ObjectInputStream(new BufferedInputStream(
            new FileInputStream(new File("E:\\workspace\\TestProject\\src\\license\\private.key"))));
    try {
        BigInteger m = (BigInteger) oin.readObject();
        BigInteger e = (BigInteger) oin.readObject();
        RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(m, e);
        KeyFactory fact = KeyFactory.getInstance("RSA");
        return fact.generatePrivate(keySpec);
    } finally {
        //         oin.close();
    }
}

From source file:com.torresbueno.RSAEncryptionDecryptionUtil.java

/**
 * read Public Key From File/*w  w  w .j a va  2 s  .com*/
 * @param filePath
 * @return PublicKey
 * @throws IOException
 */
public PublicKey readPublicKeyFromFile(String filePath) throws Exception {
    // Read file to a byte array.
    Path path = Paths.get(filePath);
    byte[] pubKeyByteArray = Files.readAllBytes(path);
    X509EncodedKeySpec spec = new X509EncodedKeySpec(pubKeyByteArray);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    return kf.generatePublic(spec);
}

From source file:SecureConnection.java

private byte[] generateSecret(byte[] otherPubKeyBytes) throws Exception {
    KeyFactory keyFac = KeyFactory.getInstance("DH");
    X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(otherPubKeyBytes);
    PublicKey otherPubKey = keyFac.generatePublic(x509KeySpec);
    this.keyAgree.doPhase(otherPubKey, true);
    return keyAgree.generateSecret();
}

From source file:org.bedework.util.security.pki.PKITools.java

/**
 * @param pubKeyBytes//w w  w  .j  av a 2 s. c om
 * @param item
 * @return encrypted value
 * @throws PKIException
 */
public String encrypt(final byte[] pubKeyBytes, final String item) throws PKIException {
    byte[] encryptedItem = null;
    Cipher asymmetricCipher;

    try {
        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pubKeyBytes);
        Key publicKey;

        if (curSchema.pName == null) {
            KeyFactory kf = KeyFactory.getInstance(curSchema.algorithm);
            publicKey = kf.generatePublic(publicKeySpec);

            asymmetricCipher = Cipher.getInstance(curSchema.algorithm);
        } else {
            KeyFactory kf = KeyFactory.getInstance(curSchema.algorithm, curSchema.pName);
            publicKey = kf.generatePublic(publicKeySpec);

            asymmetricCipher = Cipher.getInstance(curSchema.algorithm, curSchema.pName);
        }

        asymmetricCipher.init(Cipher.ENCRYPT_MODE, publicKey);
        encryptedItem = asymmetricCipher.doFinal(item.getBytes());
    } catch (Throwable t) {
        throw new PKIException(t);
    }

    return new String(b64.encode(encryptedItem));
}

From source file:io.cslinmiso.line.api.impl.LineApiImpl.java

public LoginResult login(String id, String password, String certificate) throws Exception {

    IdentityProvider provider = null;/*from w w w . ja v a 2s.  c om*/
    Map<String, String> json = null;
    String sessionKey = null;
    boolean keepLoggedIn = true;
    String accessLocation = this.ip;

    // Login to LINE server.
    if (id.matches(EMAIL_REGEX)) {
        provider = IdentityProvider.LINE; // LINE
        json = getCertResult(LINE_SESSION_LINE_URL);
    } else {
        provider = IdentityProvider.NAVER_KR; // NAVER
        json = getCertResult(LINE_SESSION_NAVER_URL);
    }

    if (id != null) {
        this.id = id;
    }

    if (password != null) {
        this.password = password;
    }

    if (StringUtils.isNotEmpty(certificate)) {
        setCertificate(certificate);
    } else {
        // read the certificate file if it exists
        try {
            List<String> readFile = Utility.readFile(LineApiImpl.CERT_FILE);
            String tmpCert = readFile != null ? readFile.get(0) : "";
            if (tmpCert != null) {
                setCertificate(tmpCert);
            }
        } catch (Exception ex) {
            setCertificate("");
        }
    }

    sessionKey = json.get("session_key");
    String tmpMsg = (char) (sessionKey.length()) + sessionKey + (char) (id.length()) + id
            + (char) (password.length()) + password;
    String message = new String(tmpMsg.getBytes(), java.nio.charset.StandardCharsets.UTF_8);
    String[] keyArr = json.get("rsa_key").split(",");
    String keyName = keyArr[0];
    String n = keyArr[1];
    String e = keyArr[2];

    BigInteger modulus = new BigInteger(n, 16);
    BigInteger pubExp = new BigInteger(e, 16);

    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(modulus, pubExp);
    RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(pubKeySpec);
    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    byte[] enBytes = cipher.doFinal(message.getBytes());
    String encryptString = Hex.encodeHexString(enBytes);

    THttpClient transport = new THttpClient(LINE_HTTP_URL);
    transport.setCustomHeaders(headers);
    transport.open();

    TProtocol protocol = new TCompactProtocol(transport);
    this.client = new TalkService.Client(protocol);

    LoginResult result = this.client.loginWithIdentityCredentialForCertificate(provider, keyName, encryptString,
            keepLoggedIn, accessLocation, this.systemName, this.certificate);

    if (result.getType() == LoginResultType.REQUIRE_DEVICE_CONFIRM) {

        headers.put("X-Line-Access", result.getVerifier());
        String pinCode = result.getPinCode();

        System.out.printf("Enter PinCode '%s' to your mobile phone in 2 minutes.\n", pinCode);
        // await for pinCode to be certified, it will return a verifier afterward.
        loginWithVerifierForCertificate();
    } else if (result.getType() == LoginResultType.SUCCESS) {
        // if param certificate has passed certification
        setAuthToken(result.getAuthToken());
    }

    // Once the client passed the verification, switch connection to HTTP_IN_URL
    this.client = ready();
    return result;
}

From source file:de.alpharogroup.crypto.key.KeyExtensions.java

/**
 * Read private key./*from   w ww  .  j av a  2 s.co m*/
 *
 * @param privateKeyBytes
 *            the private key bytes
 * @param provider
 *            the provider
 * @return the private key
 * @throws NoSuchAlgorithmException
 *             is thrown if instantiation of the cypher object fails.
 * @throws InvalidKeySpecException
 *             is thrown if generation of the SecretKey object fails.
 * @throws NoSuchProviderException
 *             is thrown if the specified provider is not registered in the security provider
 *             list.
 */
public static PrivateKey readPrivateKey(final byte[] privateKeyBytes, final String provider)
        throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException {
    final PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
    final KeyFactory keyFactory = KeyFactory.getInstance(KeyPairGeneratorAlgorithm.RSA.getAlgorithm());
    final PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
    return privateKey;
}

From source file:com.soomla.billing.Security.java

/**
 * Generates a PublicKey instance from a string containing the
 * Base64-encoded public key.//w  w w  .j av  a2s  . c  om
 *
 * @param encodedPublicKey Base64-encoded public key
 * @throws IllegalArgumentException if encodedPublicKey is invalid
 */
public static PublicKey generatePublicKey(String encodedPublicKey) {
    try {
        byte[] decodedKey = Base64.decode(encodedPublicKey);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_FACTORY_ALGORITHM);
        return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (InvalidKeySpecException e) {
        StoreUtils.LogError(TAG, "Invalid key specification.");
        throw new IllegalArgumentException(e);
    } catch (Base64DecoderException e) {
        StoreUtils.LogError(TAG, "Base64 decoding failed.");
        throw new IllegalArgumentException(e);
    }
}