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:com.poscoict.license.service.BoardService.java

public Map<String, Object> passwordPop(HttpSession session) throws Exception {
    logger.info("get passwordPopForm");
    Map<String, Object> map = new HashMap<String, Object>();

    KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
    generator.initialize(2048);/*from   w ww . j a v a  2  s .c o m*/

    KeyPair keyPair = generator.genKeyPair();
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");

    PublicKey publicKey = keyPair.getPublic();
    PrivateKey privateKey = keyPair.getPrivate();

    // ? ? ??  ? .
    session.setAttribute("__rsaPrivateKey__", privateKey);

    //  ?  JavaScript RSA ?? .
    RSAPublicKeySpec publicSpec = (RSAPublicKeySpec) keyFactory.getKeySpec(publicKey, RSAPublicKeySpec.class);

    map.put("publicKeyModulus", publicSpec.getModulus().toString(16));
    map.put("publicKeyExponent", publicSpec.getPublicExponent().toString(16));
    logger.info("return passwordPopForm");
    return map;
}

From source file:com.clustercontrol.util.KeyCheck.java

/**
 * ?//from  ww  w  .j  a v a2s  . com
 * com.clustercontrol.key.KeyGenerator????????public??
 * @param str
 * @return
 * @throws HinemosUnknown
 */
public static PublicKey getPublicKey(String str) throws HinemosUnknown {
    try {
        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(string2Byte(str));
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
        return keyFactory.generatePublic(publicKeySpec);
    } catch (InvalidKeySpecException e) {
        throw new HinemosUnknown("getPublicKey fail " + e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        throw new HinemosUnknown("getPublicKey fail " + e.getMessage(), e);
    }
}

From source file:hudson.cli.Connection.java

/**
 * Verifies that we are talking to a peer that actually owns the private key corresponding to the public key we get.
 *///from w w  w  .j  a  v  a 2 s  .c om
public PublicKey verifyIdentity(byte[] sharedSecret) throws IOException, GeneralSecurityException {
    try {
        String serverKeyAlgorithm = readUTF();
        PublicKey spk = KeyFactory.getInstance(serverKeyAlgorithm).generatePublic(readKey());

        // verify the identity of the server
        Signature sig = Signature.getInstance("SHA1with" + serverKeyAlgorithm);
        sig.initVerify(spk);
        sig.update(spk.getEncoded());
        sig.update(sharedSecret);
        sig.verify((byte[]) readObject());

        return spk;
    } catch (ClassNotFoundException e) {
        throw new Error(e); // impossible
    }
}

From source file:jfabrix101.billing.BillingSecurity.java

/**
 * Generates a PublicKey instance from a string containing the
 * Base64-encoded public key./*from   w  w  w  .  ja v a  2 s  . c  o  m*/
 *
 * @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) {
        Log.e(TAG, "Invalid key specification.");
        throw new IllegalArgumentException(e);
    } catch (Exception e) {
        Log.e(TAG, "Base64 decoding failed.");
        throw new IllegalArgumentException(e);
    }
}

From source file:net.jmhertlein.core.crypto.Keys.java

/**
 * Given a Base64-encoded, X509-formatted RSA public key, returns a PublicKey object representing it
 *
 * @param encodedKey//  w  w  w.  j av a2 s  .  co  m
 *
 * @return the RSA public key, or null if the RSA algorithm is not available on the system
 */
public static PublicKey getPublicKeyFromBASE64X509Encoded(String encodedKey) {
    byte[] decoded = Base64.decodeBase64(encodedKey);

    try {
        return KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
    } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) {
        Logger.getLogger(Keys.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}

From source file:com.aqnote.shared.cryptology.cert.gen.CertGenerator.java

public X509Certificate signCert(PKCS10CertificationRequest pkcs10CSR, X500Name issuer, KeyPair pKeyPair)
        throws Exception {
    SubjectPublicKeyInfo pkInfo = pkcs10CSR.getSubjectPublicKeyInfo();
    RSAKeyParameters rsa = (RSAKeyParameters) PublicKeyFactory.createKey(pkInfo);
    RSAPublicKeySpec rsaSpec = new RSAPublicKeySpec(rsa.getModulus(), rsa.getExponent());
    KeyFactory kf = KeyFactory.getInstance(ALG_RSA);
    PublicKey publicKey = kf.generatePublic(rsaSpec);

    SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo(ASN1Sequence.getInstance(publicKey.getEncoded()));
    X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuer,
            BigInteger.valueOf(System.currentTimeMillis()),
            new Date(System.currentTimeMillis() - DateConstant.ONE_DAY),
            new Date(System.currentTimeMillis() + DateConstant.ONE_YEAR), pkcs10CSR.getSubject(), keyInfo);

    ContentSigner signer = new JcaContentSignerBuilder(ALG_SIG_SHA256_RSA).setProvider(JCE_PROVIDER)
            .build(pKeyPair.getPrivate());
    X509Certificate signedCert = new JcaX509CertificateConverter().setProvider(JCE_PROVIDER)
            .getCertificate(certBuilder.build(signer));
    signedCert.verify(pKeyPair.getPublic());

    return signedCert;
}

From source file:org.oscarehr.common.hl7.v2.oscar_to_oscar.SendingUtils.java

/**
 * I know it returns a "private key" object but in reality it's a public key
 * because it's a key we give out to other people.
 *//*w ww . j a  va 2s . c  o  m*/
public static PrivateKey getPublicServiceKey(String publicServiceKeyString)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(publicServiceKeyString));
    KeyFactory privKeyFactory = KeyFactory.getInstance("RSA");
    PrivateKey publicServiceKey = privKeyFactory.generatePrivate(privKeySpec);
    return publicServiceKey;
}

From source file:com.brienwheeler.apps.tomcat.TomcatBean.java

private RSAPrivateKey readKeyFile() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    String parse[] = readPEMFile(sslKeyFile, KEY_PATTERN, 2);
    if (parse == null)
        throw new IllegalArgumentException("invalid key file contents");

    if (parse[0].length() == 0) { // BEGIN PRIVATE KEY
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return (RSAPrivateKey) keyFactory.generatePrivate(new PKCS8EncodedKeySpec(Base64.decode(parse[1])));
    }//from www.j  a v  a 2  s  . c o  m

    if (parse[0].contains("RSA")) { // BEGIN RSA PRIVATE KEY
        Security.addProvider(new BouncyCastleProvider());

        PEMParser pemParser = new PEMParser(new FileReader(sslKeyFile));
        Object parsedObject = pemParser.readObject();
        if (!(parsedObject instanceof PEMKeyPair))
            throw new IllegalArgumentException("invalid key file contents");

        PEMKeyPair keyPair = (PEMKeyPair) parsedObject;
        RSAPrivateKey privateKey = (RSAPrivateKey) BouncyCastleProvider
                .getPrivateKey(keyPair.getPrivateKeyInfo());
        if (privateKey == null)
            throw new IllegalArgumentException("invalid key file contents");
        return privateKey;
    }

    throw new IllegalArgumentException("invalid key file contents");
}

From source file:in.neoandroid.neoupdate.neoUpdate.java

private boolean checkSignature(String jsonContent, String sign) {
    Log.d(TAG, "JSON: " + jsonContent);

    if (sign == null)
        return false;
    final String publicKeyStr = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAq+6EG/fAE+zIdh5Wzqnf"
            + "Fo4nCf7t7eJcKyvk1lqX1MdkIi/fUs8HQ4aQ4jWLCO4M1Gkz1FQiXOnheGLV5MXY"
            + "c9GyaglsofvpA/pU5d16FybX2pCevbTzcm39eU+XlwQWOr8gh23tYD8G6uMX6sIJ"
            + "W+1k1FWdud9errMVm0YUScI+J4AV5xzN0IQ29h9IeNp6oFqZ2ByWog6OBMTUDFIW"
            + "q8oRvH0OuPv3zFR5rKwsbTYb5Da8lhUht04dLBA860Y4zeUu98huvS9jQPu2N4ns"
            + "Hf425FfDJ/wae+7eLdQo7uFb+Wvc+PO9U39e6vXQfa8ZkUoXHD0XZN4jsFcKYuJw" + "OwIDAQAB";
    try {//  ww  w  .  j a v a 2 s .c  o  m
        byte keyBytes[] = Base64.decode(publicKeyStr.getBytes(), Base64.NO_WRAP);

        X509EncodedKeySpec publicSpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PublicKey publicKey = kf.generatePublic(publicSpec);

        Signature signer = Signature.getInstance("SHA1withRSA");
        signer.initVerify(publicKey);
        signer.update(jsonContent.getBytes(), 0, jsonContent.length());

        return signer.verify(Base64.decode(sign, Base64.NO_WRAP));
    } catch (Exception e) {
    }
    return false;
}