List of usage examples for java.security KeyFactory getInstance
public static KeyFactory getInstance(String algorithm) throws NoSuchAlgorithmException
From source file:net.arccotangent.pacchat.net.ConnectionHandler.java
public void run() { try {/*from ww w .ja v a2 s . c om*/ 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:hh.learnj.test.license.test.rsacoder.RSACoder.java
/** * // 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:net.arccotangent.pacchat.filesystem.KeyManager.java
public static PublicKey loadKeyByIP(String ip_address) { km_log.i("Loading public key for " + ip_address); try {// ww w . j a va2s .com 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:de.pawlidi.openaletheia.utils.CipherUtils.java
/** * /*from ww w.j av a 2s . c o m*/ * @param data * @return */ public static RSAPrivateKey buildPrivateKey(final String key) { if (StringUtils.isNotEmpty(key)) { try { byte[] bytes = Converter.toBytes(key); KeyFactory keyFactory = KeyFactory.getInstance(CIPHER_ALGORITHM); PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(bytes); return (RSAPrivateKey) keyFactory.generatePrivate(privSpec); } catch (Exception e) { throw new RuntimeException("Cannot create " + CIPHER_ALGORITHM + " private key from " + key, e); } } return null; }
From source file:gemlite.core.util.RSAUtils.java
/** * <p>//from w w w .j a v a 2 s . co m * ????? * </p> * * @param data * ? * @param privateKey * ?(BASE64?) * * @return * @throws Exception */ public static String sign(byte[] data, String privateKey) throws Exception { byte[] keyBytes = Base64Utils.decode(privateKey); PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec); Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); signature.initSign(privateK); signature.update(data); return Base64Utils.encode(signature.sign()); }
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:com.cws.esolutions.security.dao.keymgmt.impl.FileKeyManager.java
/** * @see com.cws.esolutions.security.dao.keymgmt.interfaces.KeyManager#returnKeys(java.lang.String) *///from w w w. j a v a2s .c om public synchronized KeyPair returnKeys(final String guid) throws KeyManagementException { final String methodName = FileKeyManager.CNAME + "#returnKeys(final String guid) throws KeyManagementException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", guid); } KeyPair keyPair = null; InputStream pubStream = null; InputStream privStream = null; final File keyDirectory = FileUtils.getFile(keyConfig.getKeyDirectory() + "/" + guid); try { if (!(keyDirectory.exists())) { throw new KeyManagementException("Configured key directory does not exist and unable to create it"); } File publicFile = FileUtils .getFile(keyDirectory + "/" + guid + SecurityServiceConstants.PUBLICKEY_FILE_EXT); File privateFile = FileUtils .getFile(keyDirectory + "/" + guid + SecurityServiceConstants.PRIVATEKEY_FILE_EXT); if ((publicFile.exists()) && (privateFile.exists())) { privStream = new FileInputStream(privateFile); byte[] privKeyBytes = IOUtils.toByteArray(privStream); pubStream = new FileInputStream(publicFile); byte[] pubKeyBytes = IOUtils.toByteArray(pubStream); // files exist KeyFactory keyFactory = KeyFactory.getInstance(keyConfig.getKeyAlgorithm()); // generate private key PKCS8EncodedKeySpec privateSpec = new PKCS8EncodedKeySpec(privKeyBytes); PrivateKey privKey = keyFactory.generatePrivate(privateSpec); // generate pubkey X509EncodedKeySpec publicSpec = new X509EncodedKeySpec(pubKeyBytes); PublicKey pubKey = keyFactory.generatePublic(publicSpec); // make the keypair keyPair = new KeyPair(pubKey, privKey); } else { // files dont exist throw new KeyManagementException("Failed to locate user keys"); } } catch (FileNotFoundException fnfx) { throw new KeyManagementException(fnfx.getMessage(), fnfx); } catch (InvalidKeySpecException iksx) { throw new KeyManagementException(iksx.getMessage(), iksx); } catch (IOException iox) { throw new KeyManagementException(iox.getMessage(), iox); } catch (NoSuchAlgorithmException nsax) { throw new KeyManagementException(nsax.getMessage(), nsax); } finally { if (privStream != null) { IOUtils.closeQuietly(privStream); } if (pubStream != null) { IOUtils.closeQuietly(pubStream); } } return keyPair; }
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 ww w . j av a 2s . c om*/ 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: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);//www.j a v a2 s . c o m 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); }
From source file:org.eclipse.leshan.standalone.servlet.json.SecurityDeserializer.java
@Override public SecurityInfo deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { if (json == null) { return null; }/*w ww.j a v a 2s .c om*/ SecurityInfo info = null; if (json.isJsonObject()) { JsonObject object = (JsonObject) json; String endpoint = null; if (object.has("endpoint")) { endpoint = object.get("endpoint").getAsString(); } else { throw new JsonParseException("Missing endpoint"); } JsonObject psk = (JsonObject) object.get("psk"); JsonObject rpk = (JsonObject) object.get("rpk"); if (psk != null) { // PSK Deserialization String identity = null; if (psk.has("identity")) { identity = psk.get("identity").getAsString(); } else { throw new JsonParseException("Missing PSK identity"); } byte[] key; try { key = Hex.decodeHex(psk.get("key").getAsString().toCharArray()); } catch (DecoderException e) { throw new JsonParseException(e); } info = SecurityInfo.newPreSharedKeyInfo(endpoint, identity, key); } else if (rpk != null) { PublicKey key; try { byte[] x = Hex.decodeHex(rpk.get("x").getAsString().toCharArray()); byte[] y = Hex.decodeHex(rpk.get("y").getAsString().toCharArray()); String params = rpk.get("params").getAsString(); AlgorithmParameters algoParameters = AlgorithmParameters.getInstance("EC"); algoParameters.init(new ECGenParameterSpec(params)); ECParameterSpec parameterSpec = algoParameters.getParameterSpec(ECParameterSpec.class); KeySpec keySpec = new ECPublicKeySpec(new ECPoint(new BigInteger(x), new BigInteger(y)), parameterSpec); key = KeyFactory.getInstance("EC").generatePublic(keySpec); } catch (DecoderException | InvalidKeySpecException | NoSuchAlgorithmException | InvalidParameterSpecException e) { throw new JsonParseException("Invalid security info content", e); } info = SecurityInfo.newRawPublicKeyInfo(endpoint, key); } else { throw new JsonParseException("Invalid security info content"); } } return info; }