Example usage for java.security.spec X509EncodedKeySpec X509EncodedKeySpec

List of usage examples for java.security.spec X509EncodedKeySpec X509EncodedKeySpec

Introduction

In this page you can find the example usage for java.security.spec X509EncodedKeySpec X509EncodedKeySpec.

Prototype

public X509EncodedKeySpec(byte[] encodedKey) 

Source Link

Document

Creates a new X509EncodedKeySpec with the given encoded key.

Usage

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;// w w w.  j a v  a2  s.c om
    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);/*from  w w w.  j a v a  2  s.c o  m*/
        final X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(bytes);
        final KeyFactory factory = KeyFactory.getInstance(this.algorithm);
        return factory.generatePublic(pubSpec);
    }
}

From source file:cn.util.RSAUtils.java

/**
 * ?RSA/*from ww w  .  j a  v a2s.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:org.kde.kdeconnect.Helpers.SecurityHelpers.RsaHelper.java

public static PublicKey getPublicKey(Context context) throws Exception {
    try {//  w ww.  ja va 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:org.echocat.marquardt.example.keyprovisioning.KeyFileReadingKeyPairProvider.java

private PublicKey loadPublicKey(final String publicKeyFileName) {
    LOGGER.debug("Reading public key file {}.", publicKeyFileName);
    final byte[] keyFilePayload = readKeyFile(publicKeyFileName);
    final X509EncodedKeySpec spec = new X509EncodedKeySpec(keyFilePayload);
    try {/*  w w w .  j  a v  a  2 s. com*/
        final KeyFactory keyFactory = KeyFactory.getInstance(rsa.getJavaInternalName());
        return keyFactory.generatePublic(spec);
    } catch (final GeneralSecurityException e) {
        throw new IllegalArgumentException(
                "Failed to create public key from keyfile " + publicKeyFileName + ".", e);
    }
}

From source file:com.security.ch08_rsa.RSACoderTextKey.java

/**
 * /*from   w ww. j a  va 2 s .c o m*/
 *
 * @param data
 *            ?
 * @param key
 *            
 * @return byte[] ?
 * @throws Exception
 */
private static byte[] decryptByPublicKey(byte[] data, byte[] key) throws Exception {

    // ?
    X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);

    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

    // ?
    PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);

    // ?
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());

    cipher.init(Cipher.DECRYPT_MODE, publicKey);

    return cipher.doFinal(data);
}

From source file:com.joyent.manta.client.crypto.SecretKeyUtils.java

/**
 * Writes the specified key in X509 encoding to a stream. Note: This method
 * doesn't close the supplied stream./*  ww w.  j av  a  2  s. c o  m*/
 *
 * @param key key to write
 * @param out output stream to write to
 * @throws IOException thrown when there is a problem writing the key
 */
public static void writeKey(final SecretKey key, final OutputStream out) throws IOException {
    Validate.notNull(key, "Key must not be null");
    Validate.notNull(out, "OutputStream must not be null");
    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(key.getEncoded());
    out.write(x509EncodedKeySpec.getEncoded());
}

From source file:pl.kotcrab.crypto.CryptoUtils.java

/** Generates PublicKey from encoded bytes of X509EncodedKeySpec. Bytes must be in Base64 string.
 * @param base64 Key from encoded bytes of {@link X509EncodedKeySpec#getEncoded()}. Encoded in Base64 string.
 * @return created public key *///from w  ww  .j ava2 s . c  o  m
public static PublicKey getRSAPublicKeyFromString64(String base64) {
    try {
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.decodeBase64(base64));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
        return keyFactory.generatePublic(keySpec);
    } catch (GeneralSecurityException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:com.dev.cty.utils.googleplay.Security.java

/**
 * Generates a PublicKey instance from a string containing the
 * Base64-encoded public key.//from   w w  w  . j  a v a2  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) {
        logger.info("Invalid key specification.");
        throw new IllegalArgumentException(e);
    } catch (Base64DecoderException e) {
        logger.info("Base64 decoding failed.");
        throw new IllegalArgumentException(e);
    }
}

From source file:com.nexmo.client.auth.JWTAuthMethodTest.java

@Test
public void testConstructToken() throws Exception {
    String constructedToken = auth.constructToken(1234, "1111111");

    byte[] keyBytes = testUtils.loadKey("test/keys/application_public_key.der");
    X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PublicKey key = kf.generatePublic(spec);

    final JWTVerifier verifier = new JWTVerifier(key);
    final Map<String, Object> claims = verifier.verify(constructedToken);

    assertEquals(1234, claims.get("iat"));
    assertEquals("1111111", claims.get("jti"));
    assertEquals("application-id", claims.get("application_id"));
}