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.ConnectionHandler.java

public void run() {
    try {//w ww .j  ava  2  s  .c  o m
        String line1 = input.readLine();
        switch (line1) {
        case "101 ping":
            ch_log.i("Client pinged us, responding with an acknowledgement.");
            output.write("102 pong");
            output.newLine();
            output.flush();
            output.close();
            break;
        case "302 request key update":
            ch_log.i("Client is requesting a key update.");
            KeyUpdate update = new KeyUpdate(ip);
            KeyUpdateManager.addPendingUpdate(connection_id, update);
            while (KeyUpdateManager.getUpdate(connection_id).isProcessed()) {
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            boolean accepted = KeyUpdateManager.getUpdate(connection_id).isAccepted();
            KeyUpdateManager.completeIncomingUpdate(connection_id, KeyUpdateManager.getUpdate(connection_id));
            if (accepted) {
                ch_log.i("Accepting key update");
                try {
                    output.write("303 update");
                    output.newLine();
                    output.flush();

                    String pubkeyB64 = input.readLine();

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

                    output.close();
                    input.close();

                    KeyManager.saveKeyByIP(ip, keyFactory.generatePublic(pubSpec));
                } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
                    ch_log.e("Error updating sender's key!");
                    e.printStackTrace();
                }
            } else {
                ch_log.i("Rejecting key update.");
                output.write("304 no update");
                output.newLine();
                output.flush();
                output.close();
            }
            break;
        case "301 getkey":
            ch_log.i("Client requested our public key, sending.");
            String pubkeyB64 = Base64.encodeBase64String(Main.getKeypair().getPublic().getEncoded());
            output.write(pubkeyB64);
            output.newLine();
            output.flush();
            output.close();
            break;
        case "200 encrypted message": //incoming encrypted message
            ch_log.i("Client sent an encrypted message, attempting verification and decryption.");
            PrivateKey privkey = Main.getKeypair().getPrivate();
            String cryptedMsg = input.readLine() + "\n" + input.readLine() + "\n" + input.readLine();

            ch_log.i("Checking for sender's public key.");
            if (KeyManager.checkIfIPKeyExists(ip)) {
                ch_log.i("Public key found.");
            } else {
                ch_log.i("Public key not found, requesting key from their server.");
                try {
                    Socket socketGetkey = new Socket();
                    socketGetkey.connect(new InetSocketAddress(InetAddress.getByName(ip), 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 sender_pubkeyB64 = inputGetkey.readLine();
                    byte[] pubEncoded = Base64.decodeBase64(sender_pubkeyB64);
                    X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubEncoded);
                    KeyFactory keyFactory = KeyFactory.getInstance("RSA");

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

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

            PacchatMessage message = MsgCrypto.decryptAndVerifyMessage(cryptedMsg, privkey,
                    KeyManager.loadKeyByIP(ip));

            String msg = message.getMessage();
            boolean verified = message.isVerified();
            boolean decrypted = message.isDecryptedSuccessfully();

            String ANSI_RESET = "\u001B[0m";
            String ANSI_CYAN = "\u001B[36m";
            String ANSI_BOLD = "\u001B[1m";
            if (verified && decrypted) {
                ch_log.i("Acknowledging message.");
                output.write("201 message acknowledgement");
                output.newLine();
                output.flush();
                output.close();
                System.out.println(ANSI_BOLD + ANSI_CYAN + "-----BEGIN MESSAGE-----" + ANSI_RESET);
                System.out.println(ANSI_BOLD + ANSI_CYAN + msg + ANSI_RESET);
                System.out.println(ANSI_BOLD + ANSI_CYAN + "-----END MESSAGE-----" + ANSI_RESET);
            } else if (!verified && decrypted) {
                ch_log.w("Notifying client that message authenticity was not verified.");
                output.write("203 unable to verify");
                output.newLine();
                output.flush();
                output.close();
                System.out.println(ANSI_BOLD + ANSI_CYAN + "-----BEGIN MESSAGE-----" + ANSI_RESET);
                System.out.println(ANSI_BOLD + ANSI_CYAN + msg + ANSI_RESET);
                System.out.println(ANSI_BOLD + ANSI_CYAN + "-----END MESSAGE-----" + ANSI_RESET);
            } else if (!verified) {
                ch_log.w("Notifying client that message could not be decrypted.");
                output.write("202 unable to decrypt");
                output.newLine();
                output.flush();
                output.close();
            }
            break;
        case "201 message acknowledgement":
            ch_log.i("Client sent an invalid message acknowledgement.");
            output.write("400 invalid transmission header");
            output.newLine();
            output.flush();
            output.close();
        case "202 unable to decrypt":
            ch_log.i("Client sent an invalid 'unable to decrypt' transmission.");
            output.write("400 invalid transmission header");
            output.newLine();
            output.flush();
            output.close();
        case "203 unable to verify":
            ch_log.i("Client sent an invalid 'unable to verify' transmission.");
            output.write("400 invalid transmission header");
            output.newLine();
            output.flush();
            output.close();
        default:
            ch_log.i("Client sent an invalid request header: " + line1);
            output.write("400 invalid transmission header");
            output.newLine();
            output.flush();
            output.close();
            break;
        }
    } catch (IOException e) {
        ch_log.e("Error in connection handler " + connection_id);
        e.printStackTrace();
    }
}

From source file:net.arccotangent.pacchat.filesystem.KeyManager.java

public static PublicKey loadKeyByIP(String ip_address) {
    km_log.i("Loading public key for " + ip_address);
    try {/*from   w  w w .j  a va2 s .  c om*/
        File pubFile = new File(installationPath + File.separator + ip_address + ".pub");

        byte[] pubEncoded = Files.readAllBytes(pubFile.toPath());
        X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(Base64.decodeBase64(pubEncoded));

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePublic(pubSpec);
    } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException e) {
        km_log.e("Error while loading public key for " + ip_address + "!");
        e.printStackTrace();
    }
    return null;
}

From source file:org.sonatype.sisu.encryptor.RsaAesEncryptor.java

protected PublicKey readPublicKey(InputStream keyInput) throws IOException, GeneralSecurityException {
    InputStream input = new Base64InputStream(keyInput);
    byte[] encKey = IOUtil.toByteArray(input);
    IOUtil.close(input);/*from   w  w  w .j a  va 2 s .  c  om*/

    X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(encKey);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);

    return pubKey;
}

From source file:com.yazino.web.payment.googlecheckout.AndroidInAppOrderSecurity.java

private PublicKey generatePublicKey(String gameType, final Partner partnerId) {
    PublicKey publicKey = null;/* w ww .  ja  v  a  2  s. co m*/
    String normalisedPartnerId = getNormalisedPartnerId(partnerId);
    final String licenseKey = yazinoConfiguration
            .getString(format(CONFIG_PREFIX, normalisedPartnerId, gameType));
    if (licenseKey == null) {
        LOG.error("No license key found for gameType {}", gameType);
    } else {
        try {
            byte[] decodedKey = Base64.decode(licenseKey.getBytes());
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_FACTORY_ALGORITHM);
            publicKey = keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));
        } catch (Exception e) {
            LOG.error("Failed to decode licenseKey [{}] for gameType {}", licenseKey, gameType, e);
        }
    }
    return publicKey;
}

From source file:mitm.common.security.certificate.GenerateTestCA.java

private PublicKey decodePublicKey(String encoded) throws Exception {
    byte[] rawKey = Hex.decodeHex(encoded.toCharArray());

    KeySpec keySpec = new X509EncodedKeySpec(rawKey);

    return keyFactory.generatePublic(keySpec);
}

From source file:org.esupportail.papercut.services.PayBoxService.java

public void setDerPayboxPublicKeyFile(String derPayboxPublicKeyFile)
        throws NoSuchAlgorithmException, InvalidKeySpecException, IOException {
    org.springframework.core.io.Resource derPayboxPublicKeyRessource = new ClassPathResource(
            derPayboxPublicKeyFile);//from  w  w  w.j  a  v  a  2 s . com
    InputStream fis = derPayboxPublicKeyRessource.getInputStream();
    DataInputStream dis = new DataInputStream(fis);
    byte[] pubKeyBytes = new byte[fis.available()];
    dis.readFully(pubKeyBytes);
    fis.close();
    dis.close();
    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(pubKeyBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    this.payboxPublicKey = kf.generatePublic(x509EncodedKeySpec);
}

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

private PublicKey getPublicKeyFromString(String key) throws Exception {
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(Base64.decodeBase64(key));
    PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
    return publicKey;
}

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

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

    // 
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    // ?
    // ???
    X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);
    // 
    PublicKey pubKey = keyFactory.generatePublic(x509KeySpec);
    // ?
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.DECRYPT_MODE, pubKey);
    return cipher.doFinal(data);
}

From source file:sec_algo.commonenc.java

/**
 * Encrypts the AES key to a file using an RSA public key
 *//*w ww.j  a v a 2 s  .  c o  m*/
public void saveKey(File out, File publicKeyFile) {
    try {
        // read public key to be used to encrypt the AES key
        byte[] encodedKey = new byte[(int) publicKeyFile.length()];
        new FileInputStream(publicKeyFile).read(encodedKey);

        // create public key
        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedKey);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PublicKey pk = kf.generatePublic(publicKeySpec);

        // write AES key
        pkCipher.init(Cipher.ENCRYPT_MODE, pk);
        CipherOutputStream os = new CipherOutputStream(new FileOutputStream(out), pkCipher);
        os.write(key);
        os.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:jenkins.plugins.mailer.tasks.MimeMessageBuilderTest.java

@Test
public void test_construction() throws Exception {
    MimeMessageBuilder messageBuilder = new MimeMessageBuilder();

    messageBuilder.addRecipients("tom.xxxx@gmail.com, tom.yyyy@gmail.com");
    MimeMessage mimeMessage = messageBuilder.buildMimeMessage();

    // check from and reply-to
    Address[] from = mimeMessage.getFrom();
    Assert.assertNotNull(from);/*  ww w.  j  ava  2  s .com*/
    Assert.assertEquals(1, from.length);
    Assert.assertEquals(A, from[0].toString());
    Address[] replyTo = mimeMessage.getReplyTo();
    Assert.assertNotNull(from);
    Assert.assertEquals(1, replyTo.length);
    Assert.assertEquals(A, replyTo[0].toString());

    // check the recipient list...
    Address[] allRecipients = mimeMessage.getAllRecipients();
    Assert.assertNotNull(allRecipients);
    Assert.assertEquals(2, allRecipients.length);
    Assert.assertEquals(X, allRecipients[0].toString());
    Assert.assertEquals(Y, allRecipients[1].toString());

    // Make sure we can regen the instance identifier public key
    String encodedIdent = mimeMessage.getHeader("X-Instance-Identity")[0];
    byte[] image = Base64.decodeBase64(encodedIdent);
    PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(image));
    Assert.assertNotNull(publicKey);
}