List of usage examples for java.security KeyFactory generatePublic
public final PublicKey generatePublic(KeySpec keySpec) throws InvalidKeySpecException
From source file:com.zxy.commons.codec.rsa.RSAUtils.java
/** * <p>/* w w w. j av a 2 s. c o m*/ * * </p> * * @param encryptedData ? * @param publicKey (BASE64?) * @return byte * @throws Exception Exception */ public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey) throws Exception { byte[] keyBytes = Base64.decodeBase64(publicKey); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); Key publicK = keyFactory.generatePublic(x509KeySpec); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, publicK); int inputLen = encryptedData.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int index = 0; // ? while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_DECRYPT_BLOCK) { cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK); } else { cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); index++; offSet = index * MAX_DECRYPT_BLOCK; } byte[] decryptedData = out.toByteArray(); out.close(); return decryptedData; }
From source file:com.zxy.commons.codec.rsa.RSAUtils.java
/** * <p>/*w ww .j a va 2 s. com*/ * * </p> * * @param data ?? * @param publicKey (BASE64?) * @return byte * @throws Exception Exception */ public static byte[] encryptByPublicKey(byte[] data, String publicKey) throws Exception { byte[] keyBytes = Base64.decodeBase64(publicKey); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); Key publicK = keyFactory.generatePublic(x509KeySpec); // ? Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, publicK); int inputLen = data.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int index = 0; // ? while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_ENCRYPT_BLOCK) { cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK); } else { cache = cipher.doFinal(data, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); index++; offSet = index * MAX_ENCRYPT_BLOCK; } byte[] encryptedData = out.toByteArray(); out.close(); return encryptedData; }
From source file:edu.internet2.middleware.openid.message.encoding.EncodingUtils.java
/** * Decode a DH public key.//from w w w . j a v a2s.c o m * * @param encodedKey public key to decode * @param parameters DH parameters used in decoding * @return decoded public key * @throws NoSuchAlgorithmException if DH algorithm is unavailable * @throws InvalidKeySpecException if unable to build a valid DH key spec */ public static DHPublicKey decodePublicKey(String encodedKey, DHParameterSpec parameters) throws NoSuchAlgorithmException, InvalidKeySpecException { byte[] keyBytes = Base64.decodeBase64(encodedKey.getBytes()); DHPublicKeySpec keySpec = new DHPublicKeySpec(new BigInteger(keyBytes), parameters.getP(), parameters.getG()); KeyFactory keyFactory = KeyFactory.getInstance("DH"); return (DHPublicKey) keyFactory.generatePublic(keySpec); }
From source file:license.TestWakeLicense.java
/** * ?/* w w w .ja va2 s. c o m*/ * @return * @throws Exception */ static PublicKey readPublicKeyFromFile() throws Exception { ObjectInputStream oin = new ObjectInputStream(new ByteArrayInputStream(KeyData.publicKey)); try { BigInteger m = (BigInteger) oin.readObject(); BigInteger e = (BigInteger) oin.readObject(); RSAPublicKeySpec keySpec = new RSAPublicKeySpec(m, e); KeyFactory fact = KeyFactory.getInstance("RSA"); return fact.generatePublic(keySpec); } finally { oin.close(); } }
From source file:cn.mrdear.pay.util.RSAUtils.java
/** * ?//from ww w . ja va2s . c o m * * @param encodedKey * ? * @return */ public static PublicKey generatePublicKey(byte[] encodedKey) { Assert.notNull(encodedKey); try { KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM, PROVIDER); return keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey)); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e.getMessage(), e); } catch (InvalidKeySpecException e) { throw new RuntimeException(e.getMessage(), e); } }
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;//www . ja v a 2 s.co 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:com.vmware.identity.openidconnect.sample.RelyingPartyInstaller.java
static PublicKey loadPublicKey(String file, String algorithm) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { // Read Public Key. File filePublicKey = new File(file); FileInputStream fis = new FileInputStream(file); byte[] encodedPublicKey = new byte[(int) filePublicKey.length()]; fis.read(encodedPublicKey);/* ww w . j av a 2s. com*/ fis.close(); // Generate Public Key. KeyFactory keyFactory = KeyFactory.getInstance(algorithm); X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedPublicKey); PublicKey publicKey = keyFactory.generatePublic(publicKeySpec); return publicKey; }
From source file:br.edu.ufcg.lsd.commune.network.signature.Util.java
public static PublicKey decodePublicKey(String pubKeyStr) throws InvalidKeySpecException { byte[] binaryArray = decodeStringOnBase64(pubKeyStr); KeyFactory keyFactory; try {// w w w. j a v a2s. com keyFactory = KeyFactory.getInstance(SignatureConstants.KEY_GEN_ALGORITHM); } catch (NoSuchAlgorithmException e) { //We're assuming that we are always instantiating a valid algorithm throw new CommuneRuntimeException(e); } EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(binaryArray); return keyFactory.generatePublic(publicKeySpec); }
From source file:org.apache.cloudstack.utils.auth.SAMLUtils.java
public static PublicKey loadPublicKey(String publicKey) { byte[] sigBytes = org.bouncycastle.util.encoders.Base64.decode(publicKey); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(sigBytes); KeyFactory keyFact = SAMLUtils.getKeyFactory(); if (keyFact == null) return null; try {// ww w . java2s. c om return keyFact.generatePublic(x509KeySpec); } catch (InvalidKeySpecException e) { s_logger.error("Unable to create PrivateKey from privateKey string:" + e.getMessage()); } return null; }
From source file:net.padlocksoftware.padlock.KeyManager.java
/** * Import a Padlock 2.x (DSA based) KeyPair from an InputStream. The stream is * assumed to have been previously exported in a supported format using the * exportKeyPair methods./*from ww w . j a v a2s.co m*/ * @param stream The KeyPair stream to import. * @return The DSA KeyPair contained in the specified file. * @throws java.io.IOException If file is missing or contain invalid data. * @since 2.0 */ public static KeyPair importKeyPair(InputStream stream) throws IOException { if (stream == null) throw new IllegalArgumentException("Stream cannot be null"); KeyPair pair = null; Properties p = new Properties(); p.load(stream); stream.close(); String pri = p.getProperty("private"); String pub = p.getProperty("public"); if (pri == null || pub == null) { throw new IOException("Stream data is invalid"); } // Load the keys try { PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(Hex.decodeHex(pri.toCharArray())); KeyFactory keyFactory = KeyFactory.getInstance("DSA"); PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec); X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(Hex.decodeHex(pub.toCharArray())); PublicKey publicKey = keyFactory.generatePublic(pubSpec); pair = new KeyPair(publicKey, privateKey); } catch (Exception e) { throw new RuntimeException("Invalid stream: " + e.getMessage()); } return pair; }