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.vexsoftware.votifier.util.rsa.RSAIO.java

/**
 * Loads an RSA public key from a URL./* ww  w  .j  ava 2  s.c om*/
 * 
 * @param url
 *            The URL that has the public key
 * @return
 *            The public key
 * @throws Exception
 *            If an error occurs
 */
public static PublicKey loadPublicKey(URL url) throws Exception {
    String publicKey = new String(IOUtils.toByteArray(url), "UTF-8")
            .replaceAll("(-+BEGIN PUBLIC KEY-+\\r?\\n|-+END PUBLIC KEY-+\\r?\\n?)", "");
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(DatatypeConverter.parseBase64Binary(publicKey));
    return keyFactory.generatePublic(publicKeySpec);
}

From source file:com.google.jenkins.plugins.credentials.oauth.JsonServiceAccountConfig.java

@Override
public PrivateKey getPrivateKey() {
    JsonKey jsonKey = getJsonKey();//from  w  w  w.  ja  va  2 s .com
    if (jsonKey != null) {
        String privateKey = jsonKey.getPrivateKey();
        if (privateKey != null && !privateKey.isEmpty()) {
            PemReader pemReader = new PemReader(new StringReader(privateKey));
            try {
                PemReader.Section section = pemReader.readNextSection();
                PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(section.getBase64DecodedBytes());
                return KeyFactory.getInstance("RSA").generatePrivate(keySpec);
            } catch (IOException e) {
                LOGGER.log(Level.SEVERE, "Failed to read private key", e);
            } catch (InvalidKeySpecException e) {
                LOGGER.log(Level.SEVERE, "Failed to read private key", e);
            } catch (NoSuchAlgorithmException e) {
                LOGGER.log(Level.SEVERE, "Failed to read private key", e);
            }
        }
    }
    return null;
}

From source file:com.sammyun.util.RSAUtils.java

/**
 * RSA??/*from  w ww. j  av a 2  s . co  m*/
 * 
 * @param content ???
 * @param sign ??
 * @param ali_public_key ?
 * @param input_charset ??
 * @return 
 */
public static boolean verify(String content, String sign, String ali_public_key, String input_charset) {
    try {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] encodedKey = Base64Util.decode(ali_public_key);
        PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));

        java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);

        signature.initVerify(pubKey);
        signature.update(content.getBytes(input_charset));
        boolean bverify = signature.verify(Base64Util.decode(sign));
        return bverify;

    } catch (Exception e) {
        e.printStackTrace();
    }

    return false;
}

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

/**
 * //ww w. jav  a 2 s .c  om
 * 
 * 
 * @param info ?
 * @return ?
 * @throws GeneralSecurityException GeneralSecurityException
 */
public String encode(String info) throws GeneralSecurityException {
    // ?token?
    byte[] pubKeyText = this.getPubKeyText();
    X509EncodedKeySpec bobPKeySpec = new X509EncodedKeySpec(Base64.decodeBase64(pubKeyText));
    KeyFactory keyFactory = null;
    if (provider == null) {
        keyFactory = KeyFactory.getInstance(ALGORITHM);
    } else {
        keyFactory = KeyFactory.getInstance(ALGORITHM, provider);
    }
    // ?
    PublicKey pubkey = keyFactory.generatePublic(bobPKeySpec);
    // CipherECB?PKCS5Padding
    Cipher cipher = null;
    if (provider == null) {
        cipher = Cipher.getInstance(ALGORITHM);
    } else {
        cipher = Cipher.getInstance(ALGORITHM, provider);
    }
    // ?
    cipher.init(Cipher.ENCRYPT_MODE, pubkey);
    byte[] cipherText = cipher.doFinal(info.getBytes());
    return new String(Base64.encodeBase64(cipherText));
}

From source file:org.apache.jmeter.protocol.oauth.sampler.PrivateKeyReader.java

/**
 * Read the PEM file and return the key//from  w w  w.ja  v a  2s. c o m
 * 
 * @return
 * @throws IOException
 */
private PrivateKey read() throws IOException {

    String line;

    KeyFactory factory;
    try {
        factory = KeyFactory.getInstance("RSA"); //$NON-NLS-1$
    } catch (NoSuchAlgorithmException e) {
        throw new IOException("JCE error: " + e.getMessage()); //$NON-NLS-1$
    }

    while ((line = server.readLine(fileName)) != null) {
        if (line.indexOf(P1_BEGIN_MARKER) != -1) {
            byte[] keyBytes = readKeyMaterial(P1_END_MARKER);
            RSAPrivateCrtKeySpec keySpec = getRSAKeySpec(keyBytes);

            try {
                return factory.generatePrivate(keySpec);
            } catch (InvalidKeySpecException e) {
                throw new IOException("Invalid PKCS#1 PEM file: " + e.getMessage()); //$NON-NLS-1$
            }
        }

        if (line.indexOf(P8_BEGIN_MARKER) != -1) {
            byte[] keyBytes = readKeyMaterial(P8_END_MARKER);
            EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);

            try {
                return factory.generatePrivate(keySpec);
            } catch (InvalidKeySpecException e) {
                throw new IOException("Invalid PKCS#8 PEM file: " + e.getMessage()); //$NON-NLS-1$
            }
        }

    }

    throw new IOException("Invalid PEM file: no begin marker"); //$NON-NLS-1$
}

From source file:com.cedarsoft.crypt.CertTest.java

@Test
public void testKey() throws Exception {
    InputStream inStream = new DataInputStream(getClass().getResource("/test.der").openStream());
    byte[] keyBytes = new byte[inStream.available()];
    inStream.read(keyBytes);//from  w  w  w .  ja  v  a  2  s  .c  o m
    inStream.close();

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

    // decipher private key
    PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(keyBytes);
    RSAPrivateKey privKey = (RSAPrivateKey) keyFactory.generatePrivate(privSpec);
    assertNotNull(privKey);

    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, privKey);

    byte[] bytes = cipher.doFinal(PLAINTEXT.getBytes());
    assertEquals(SCRAMBLED, new String(Base64.encodeBase64(bytes)));
}

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

private PrivateKey getPrivateKeyFromString(String key) throws Exception {

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

    EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(key));

    PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);

    return privateKey;

}

From source file:com.ss.license.LicenseManager.java

/**
 * license/*  w  ww. ja v  a2s .  c o m*/
 * Mac
 * 
 * 
 * @param license
 * @return
 * @throws Exception
 */
boolean validate(License license) throws Exception {
    String macAddress = license.getMacAddress();
    if (macAddress != null && macAddress.length() > 0) {
        String curMacAddress = "";
        if (!macAddress.equals(curMacAddress))
            return false;
    }
    String publicKey = FileHelper.readFile(new File(LicenseFactory.PUBLIC_KEY_FILE)).trim();

    X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(EasyUtils.decodeHex(publicKey));
    KeyFactory keyFactory = KeyFactory.getInstance("DSA");
    java.security.PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);

    Signature sig = Signature.getInstance("DSA");
    sig.initVerify(pubKey);
    sig.update(license.getFingerprint());
    return sig.verify(EasyUtils.decodeHex(license.getLicenseSignature()));
}

From source file:license.regist.ProjectInfo.java

private static PrivateKey readPrivateKeyFromFile() throws Exception {
    ObjectInputStream oin = new ObjectInputStream(
            new BufferedInputStream(ProjectInfo.class.getClassLoader().getResourceAsStream("private.key")));
    try {//  w w w  .j  a v a  2  s .  c o  m
        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.github.aynu.mosir.core.standard.util.SecurityHelper.java

/**
 * RSA???/*from w w  w  .  j  a  v a  2 s.  c o m*/
 * <dl>
 * <dt>?
 * <dd>RSA?????????????
 * </dl>
 * @param modulus 
 * @param exponent ??
 * @return RSA?
 */
public static RSAPrivateKey createPrivateKey(final BigInteger modulus, final BigInteger exponent) {
    try {
        final KeyFactory keyFactory = KeyFactory.getInstance(ALGO_KEY);
        return (RSAPrivateKey) keyFactory.generatePrivate(new RSAPrivateKeySpec(modulus, exponent));
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        throw new StandardRuntimeException(e);
    }
}