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.casbah.provider.SSLeayEncoderTest.java

private static RSAPrivateCrtKey generateKey() throws GeneralSecurityException {
    KeyFactory kf = KeyFactory.getInstance("RSA");
    RSAPrivateCrtKeySpec keyspec = new RSAPrivateCrtKeySpec(MODULUS, PUBLIC_EXPONENT, PRIVATE_EXPONENT, PRIME1,
            PRIME2, EXPONENT1, EXPONENT2, COEFFICIENT);
    return (RSAPrivateCrtKey) kf.generatePrivate(keyspec);
}

From source file:com.github.ibole.infrastructure.security.key.PemUtils.java

private static PrivateKey getPrivateKey(byte[] keyBytes, String algorithm) {
    PrivateKey privateKey = null;
    try {/*from ww w  . j  a va  2  s .c  o m*/
        KeyFactory kf = KeyFactory.getInstance(algorithm);
        EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        privateKey = kf.generatePrivate(keySpec);
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        MoreThrowables.throwIfUnchecked(e);
    }
    return privateKey;
}

From source file:org.apache.camel.component.gae.auth.GAuthPk8Loader.java

/**
 * Loads a private key from a PKCS#8 file.
 *///from ww w.j a  v  a2  s  . co  m
public PrivateKey loadPrivateKey() throws Exception {
    String str = IOUtils.toString(keyLocation.getInputStream());

    if (str.contains(BEGIN) && str.contains(END)) {
        str = str.substring(BEGIN.length(), str.lastIndexOf(END));
    }

    KeyFactory factory = KeyFactory.getInstance("RSA");
    return factory.generatePrivate(new PKCS8EncodedKeySpec(Base64.decode(str)));
}

From source file:com.spotify.sshagentproxy.RSA.java

/**
 * Create an {@link RSAPublicKey} from bytes.
 * @param key Array of bytes representing RSA public key.
 * @return {@link RSAPublicKey}//from   w  w  w  . j a  va  2s .c o m
 * @throws InvalidKeyException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
static RSAPublicKey from(final byte[] key)
        throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException {

    final String s = new String(key);
    final byte[] encoded;
    final String decoded;
    if (s.startsWith(RSA_LABEL)) {
        decoded = s.split(" ")[1];
        encoded = Base64.decodeBase64(decoded);
    } else {
        encoded = key;
        decoded = Base64.encodeBase64String(key);
    }

    final Iterator<byte[]> fields = new ByteIterator(encoded);
    final String sigType = new String(fields.next());
    if (!sigType.equals(RSA_LABEL)) {
        throw new RuntimeException(String.format("Unknown key type %s. This code currently only supports %s.",
                sigType, RSA_LABEL));
    }

    final RSAPublicKeySpec keySpec = TraditionalKeyParser.parsePemPublicKey(RSA_LABEL + " " + decoded + " ");
    final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    return (RSAPublicKey) keyFactory.generatePublic(keySpec);
}

From source file:cn.util.RSAUtils.java

/**
 * ?RSA//from   w w  w  .  j  a  v a 2 s  .co m
 * ?????RSA/None/PKCS1Padding??JDK?????AndroidRSA
 * /None/NoPadding
 * 
 * @param modulus
 *            
 * @param exponent
 *            
 * @return
 */
public static RSAPublicKey getPublicKey() {
    try {
        return (RSAPublicKey) KeyFactory.getInstance("RSA")
                .generatePublic(new X509EncodedKeySpec(publickKeyData));
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.google.u2f.TestUtils.java

public static PrivateKey parsePrivateKey(String keyBytesHex) {
    try {// w w  w  .  ja va2  s.c o  m
        KeyFactory fac = KeyFactory.getInstance("ECDSA");
        X9ECParameters curve = SECNamedCurves.getByName("secp256r1");
        ECParameterSpec curveSpec = new ECParameterSpec(curve.getCurve(), curve.getG(), curve.getN(),
                curve.getH());
        ECPrivateKeySpec keySpec = new ECPrivateKeySpec(new BigInteger(keyBytesHex, 16), curveSpec);
        return fac.generatePrivate(keySpec);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (InvalidKeySpecException e) {
        throw new RuntimeException(e);
    }
}

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

public static PublicKey getPublicKey(Context context) throws Exception {
    try {//from  w  w w  . j  av  a  2s  . c  o  m
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
        byte[] publicKeyBytes = Base64.decode(settings.getString("publicKey", ""), 0);
        PublicKey publicKey = KeyFactory.getInstance("RSA")
                .generatePublic(new X509EncodedKeySpec(publicKeyBytes));
        return publicKey;
    } catch (Exception e) {
        throw e;
    }
}

From source file:net.sf.zekr.common.util.CryptoUtils.java

public static boolean verify(byte[] text, byte[] sigBytes) throws GeneralSecurityException {
    X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(PUBLIC_KEY);
    KeyFactory keyFactory = KeyFactory.getInstance("DSA");
    PublicKey pubKey = keyFactory.generatePublic(pubSpec);
    return verify(text, pubKey, sigBytes);
}

From source file:net.arccotangent.pacchat.net.Client.java

public static void sendMessage(String msg, String ip_address) {
    client_log.i("Sending message to " + ip_address);
    client_log.i("Connecting to server...");

    PublicKey pub;//from   w w w  .j  av a2 s.c o m
    PrivateKey priv;
    Socket socket;
    BufferedReader input;
    BufferedWriter output;

    client_log.i("Checking for recipient's public key...");
    if (KeyManager.checkIfIPKeyExists(ip_address)) {
        client_log.i("Public key found.");
    } else {
        client_log.i("Public key not found, requesting key from their server.");
        try {
            Socket socketGetkey = new Socket();
            socketGetkey.connect(new InetSocketAddress(InetAddress.getByName(ip_address), Server.PORT), 1000);
            BufferedReader inputGetkey = new BufferedReader(
                    new InputStreamReader(socketGetkey.getInputStream()));
            BufferedWriter outputGetkey = new BufferedWriter(
                    new OutputStreamWriter(socketGetkey.getOutputStream()));

            outputGetkey.write("301 getkey");
            outputGetkey.newLine();
            outputGetkey.flush();

            String pubkeyB64 = inputGetkey.readLine();
            byte[] pubEncoded = Base64.decodeBase64(pubkeyB64);
            X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubEncoded);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");

            outputGetkey.close();
            inputGetkey.close();

            KeyManager.saveKeyByIP(ip_address, keyFactory.generatePublic(pubSpec));
        } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException e) {
            client_log.e("Error saving recipient's key!");
            e.printStackTrace();
        }
    }

    try {
        socket = new Socket();
        socket.connect(new InetSocketAddress(InetAddress.getByName(ip_address), Server.PORT), 1000);
        input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        output = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
    } catch (SocketTimeoutException e) {
        client_log.e("Connection to server timed out!");
        e.printStackTrace();
        return;
    } catch (ConnectException e) {
        client_log.e("Connection to server was refused!");
        e.printStackTrace();
        return;
    } catch (UnknownHostException e) {
        client_log.e("You entered an invalid IP address!");
        e.printStackTrace();
        return;
    } catch (IOException e) {
        client_log.e("Error connecting to server!");
        e.printStackTrace();
        return;
    }

    try {
        Thread.sleep(100);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    pub = KeyManager.loadKeyByIP(ip_address);
    priv = Main.getKeypair().getPrivate();

    String cryptedMsg = MsgCrypto.encryptAndSignMessage(msg, pub, priv);
    try {
        client_log.i("Sending message to recipient.");
        output.write("200 encrypted message");
        output.newLine();
        output.write(cryptedMsg);
        output.newLine();
        output.flush();

        String ack = input.readLine();
        switch (ack) {
        case "201 message acknowledgement":
            client_log.i("Transmission successful, received server acknowledgement.");
            break;
        case "202 unable to decrypt":
            client_log.e(
                    "Transmission failure! Server reports that the message could not be decrypted. Did your keys change? Asking recipient for key update.");
            kuc_id++;
            KeyUpdateClient kuc = new KeyUpdateClient(kuc_id, ip_address);
            kuc.start();
            break;
        case "203 unable to verify":
            client_log.w("**********************************************");
            client_log.w(
                    "Transmission successful, but the receiving server reports that the authenticity of the message could not be verified!");
            client_log.w(
                    "Someone may be tampering with your connection! This is an unlikely, but not impossible scenario!");
            client_log.w(
                    "If you are sure the connection was not tampered with, consider requesting a key update.");
            client_log.w("**********************************************");
            break;
        case "400 invalid transmission header":
            client_log.e(
                    "Transmission failure! Server reports that the message is invalid. Try updating your software and have the recipient do the same. If this does not fix the problem, report the error to developers.");
            break;
        default:
            client_log.w("Server responded with unexpected code: " + ack);
            client_log.w("Transmission might not have been successful.");
            break;
        }

        output.close();
        input.close();
    } catch (IOException e) {
        client_log.e("Error sending message to recipient!");
        e.printStackTrace();
    }
}

From source file:org.jasig.cas.util.PublicKeyFactoryBean.java

@Override
protected final PublicKey createInstance() throws Exception {
    logger.debug("Creating public key instance from [{}] using [{}]", this.resource.getFilename(),
            this.algorithm);

    try (final InputStream pubKey = this.resource.getInputStream()) {
        final byte[] bytes = new byte[pubKey.available()];
        pubKey.read(bytes);/* w w  w  . jav a  2 s . com*/
        final X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(bytes);
        final KeyFactory factory = KeyFactory.getInstance(this.algorithm);
        return factory.generatePublic(pubSpec);
    }
}