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.sshtools.j2ssh.transport.publickey.dsa.SshDssPrivateKey.java

/**
 * Creates a new SshDssPrivateKey object.
 *
 * @param key//from   w  w w . jav  a2 s .c om
 *
 * @throws InvalidSshKeyException
 */
public SshDssPrivateKey(byte[] key) throws InvalidSshKeyException {
    try {
        DSAPrivateKeySpec dsaKey;

        // Extract the key information
        ByteArrayReader bar = new ByteArrayReader(key);

        String header = bar.readString();

        if (!header.equals(getAlgorithmName())) {
            throw new InvalidSshKeyException();
        }

        BigInteger p = bar.readBigInteger();
        BigInteger q = bar.readBigInteger();
        BigInteger g = bar.readBigInteger();
        BigInteger x = bar.readBigInteger();

        dsaKey = new DSAPrivateKeySpec(x, p, q, g);

        KeyFactory kf = KeyFactory.getInstance("DSA");
        prvkey = (DSAPrivateKey) kf.generatePrivate(dsaKey);

        log.info(prvkey.getParams().getP().toString(16));
        log.info(prvkey.getParams().getQ().toString(16));
        log.info(prvkey.getParams().getG().toString(16));
        log.info(getY().toString(16));

    } catch (Exception e) {
        throw new InvalidSshKeyException();
    }
}

From source file:org.openengsb.core.services.internal.security.FileKeySource.java

private KeyFactory getKeyFactory() {
    try {//w  w  w . j a va 2s.c  o  m
        return KeyFactory.getInstance(algorithm);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException(e);
    }
}

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  . java2s  .  com
    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.google.u2f.TestUtils.java

public static PublicKey parsePublicKey(byte[] keyBytes) {
    try {//from  w  w w. j a va 2s.c o  m
        X9ECParameters curve = SECNamedCurves.getByName("secp256r1");
        ECParameterSpec curveSpec = new ECParameterSpec(curve.getCurve(), curve.getG(), curve.getN(),
                curve.getH());
        ECPoint point = curve.getCurve().decodePoint(keyBytes);
        return KeyFactory.getInstance("ECDSA").generatePublic(new ECPublicKeySpec(point, curveSpec));
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (InvalidKeySpecException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.spotify.docker.client.DockerCertificates.java

private DockerCertificates(final Builder builder) throws DockerCertificateException {
    try {//from www  .  j  a va2s  .c o  m
        final CertificateFactory cf = CertificateFactory.getInstance("X.509");
        final Certificate caCert = cf.generateCertificate(Files.newInputStream(builder.caCertPath));
        final Certificate clientCert = cf.generateCertificate(Files.newInputStream(builder.clientCertPath));

        final PEMKeyPair clientKeyPair = (PEMKeyPair) new PEMParser(
                Files.newBufferedReader(builder.clientKeyPath, Charset.defaultCharset())).readObject();

        final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(
                clientKeyPair.getPrivateKeyInfo().getEncoded());
        final KeyFactory kf = KeyFactory.getInstance("RSA");
        final PrivateKey clientKey = kf.generatePrivate(spec);

        final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        trustStore.setEntry("ca", new KeyStore.TrustedCertificateEntry(caCert), null);

        final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);
        keyStore.setCertificateEntry("client", clientCert);
        keyStore.setKeyEntry("key", clientKey, KEY_STORE_PASSWORD, new Certificate[] { clientCert });

        this.sslContext = SSLContexts.custom().loadTrustMaterial(trustStore)
                .loadKeyMaterial(keyStore, KEY_STORE_PASSWORD).useTLS().build();
    } catch (CertificateException | IOException | NoSuchAlgorithmException | InvalidKeySpecException
            | KeyStoreException | UnrecoverableKeyException | KeyManagementException e) {
        throw new DockerCertificateException(e);
    }
}

From source file:com.sshtools.j2ssh.transport.publickey.dsa.SshDssPublicKey.java

/**
 * Creates a new SshDssPublicKey object.
 *
 * @param key/*from   w w  w  .  j a va 2s .  c  o  m*/
 *
 * @throws InvalidSshKeyException
 */
public SshDssPublicKey(byte[] key) throws InvalidSshKeyException {
    try {
        DSAPublicKeySpec dsaKey;

        // Extract the key information
        ByteArrayReader bar = new ByteArrayReader(key);

        String header = bar.readString();

        if (!header.equals(getAlgorithmName())) {
            throw new InvalidSshKeyException();
        }

        BigInteger p = bar.readBigInteger();
        BigInteger q = bar.readBigInteger();
        BigInteger g = bar.readBigInteger();
        BigInteger y = bar.readBigInteger();

        dsaKey = new DSAPublicKeySpec(y, p, q, g);

        KeyFactory kf = KeyFactory.getInstance("DSA");
        pubkey = (DSAPublicKey) kf.generatePublic(dsaKey);
    } catch (Exception e) {
        throw new InvalidSshKeyException();
    }
}

From source file:org.kde.kdeconnect.Helpers.SecurityHelpers.RsaHelper.java

public static PrivateKey getPrivateKey(Context context) throws Exception {

    try {/*from   w w  w.  j a  va  2 s  . c o  m*/
        SharedPreferences globalSettings = PreferenceManager.getDefaultSharedPreferences(context);
        byte[] privateKeyBytes = Base64.decode(globalSettings.getString("privateKey", ""), 0);
        PrivateKey privateKey = KeyFactory.getInstance("RSA")
                .generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes));
        return privateKey;
    } catch (Exception e) {
        throw e;
    }

}

From source file:com.shenit.commons.codec.RsaUtils.java

/**
 * RSA??//w  ww  . jav  a  2s.  co  m
 * 
 * @param content
 *            ???
 * @param sign
 *            ??
 * @param publicKey
 *            ?
 * @param inputCharset
 *            ??
 * @return 
 */
public static boolean verify(String content, String sign, String publicKey, String algorithm,
        String inputCharset) {
    try {
        KeyFactory keyFactory = KeyFactory.getInstance(CODEC_RSA);
        byte[] encodedKey = Base64.decodeBase64(publicKey);
        PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));

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

        signature.initVerify(pubKey);
        signature.update(content.getBytes(inputCharset));

        boolean bverify = signature.verify(Base64.decodeBase64(sign));
        return bverify;

    } catch (Exception e) {
        if (LOG.isWarnEnabled())
            LOG.warn("[verify] verify with exception", e);
    }

    return false;
}

From source file:de.mpg.escidoc.services.aa.crypto.RSAEncoder.java

public static Key readKeyFromFile(String keyFileName, boolean publ) throws Exception {
    InputStream in = ResourceUtil.getResourceAsStream(keyFileName, RSAEncoder.class.getClassLoader());
    ObjectInputStream oin = new ObjectInputStream(new BufferedInputStream(in));
    try {/* w  w  w  .  ja  va  2 s. c o m*/
        BigInteger m = (BigInteger) oin.readObject();
        BigInteger e = (BigInteger) oin.readObject();
        KeySpec keySpec;
        if (publ) {
            keySpec = new RSAPublicKeySpec(m, e);
        } else {
            keySpec = new RSAPrivateKeySpec(m, e);
        }
        KeyFactory fact = KeyFactory.getInstance("RSA");
        if (publ) {
            PublicKey pubKey = fact.generatePublic(keySpec);
            return pubKey;
        } else {
            PrivateKey privKey = fact.generatePrivate(keySpec);
            return privKey;
        }
    } catch (Exception e) {
        throw new RuntimeException("Error reading key from file", e);
    } finally {
        oin.close();
    }
}

From source file:hh.learnj.test.license.test.rsacoder.RSACoder.java

/**
 * ?//from w  w w.  j a v  a2s.  c o m
 * 
 * @param data
 *            ?
 * @param key
 *            
 * @return byte[] ?
 */
public static byte[] decryptByPrivateKey(byte[] data, byte[] key) throws Exception {
    // ??
    PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    // ??
    PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
    // ?
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.DECRYPT_MODE, privateKey);
    return cipher.doFinal(data);
}