非對稱加密擁有兩個密鑰:公開密鑰(publickey)和私有密鑰(privatekey)。一般使用公鑰加密,只有使用對應的私鑰纔可以解密。html
非對稱加密主要算法有:RSA、Elgamal、揹包算法、Rabin、D-H、ECC(橢圓曲線加密算法)等java
非對稱加密執行的步驟順序:算法
一、先獲取KeyPair對象;數組
二、獲取字符串的公鑰/私鑰;ide
三、將字符串的公鑰/私鑰轉換成爲公鑰/私鑰類對象;加密
四、使用類對象的公鑰進行數據加密;spa
五、使用類對象的私鑰進行解密。code
RSA算法orm
目前最經常使用的非對稱加密算法就是RSA算法,是Rivest, Shamir, 和Adleman於1978年發明,他們那時都是在MIT。
htm
/** * 獲取祕鑰KeyPair * @return * @throws Exception */ public static KeyPair getKeyPair() throws Exception { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(512); KeyPair keyPair = keyPairGenerator.generateKeyPair(); return keyPair; } /** * RSA 獲取String公鑰 * @param keyPair * @return */ public static String getPublicKey(KeyPair keyPair) { PublicKey publicKey = keyPair.getPublic(); byte[] bytes = publicKey.getEncoded(); return byte2base64(bytes); } /** * RSA 獲取String私鑰 * @param keyPair * @return */ public static String getPrivateKey(KeyPair keyPair) { PrivateKey privateKey = keyPair.getPrivate(); byte[] bytes = privateKey.getEncoded(); return byte2base64(bytes); } /** * RSA 將字符串轉換成爲PublicKey公鑰 * @param pubSt * @return * @throws Exception */ public static PublicKey string2PublicKey (String pubSt) throws Exception{ byte[] keyBytes = base642byte(pubSt); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PublicKey publicKey = keyFactory.generatePublic(keySpec); return publicKey; } /** * RSA 將字符串轉換成爲PrivateKey公鑰 * @param priStr * @return * @throws Exception */ public static PrivateKey string2PrivateKey(String priStr) throws Exception { byte[] keyBytes = base642byte(priStr); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PrivateKey privateKey = keyFactory.generatePrivate(keySpec); return privateKey; } /** * RSA 數據加密 * @param con * @param publicKey * @return * @throws Exception */ public static byte[] publicEncrypt(byte[] con,PublicKey publicKey) throws Exception { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); byte[] bytes = cipher.doFinal(con); return bytes; } /** * RSA 數據解密 * @param con * @param privateKey * @return * @throws Exception */ public static byte[] privateDecrypt(byte[] con,PrivateKey privateKey) throws Exception { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, privateKey); byte[] bytes = cipher.doFinal(con); return bytes; } /** * base64 編碼 * @param base64 * @return * @throws IOException */ private static byte[] base642byte(String base64) throws IOException { BASE64Decoder bs = new BASE64Decoder(); return bs.decodeBuffer(base64); } /** * base64 解碼 * @param bytes * @return */ private static String byte2base64(byte[] bytes) { BASE64Encoder bse = new BASE64Encoder(); return bse.encode(bytes); } /**將字節數組轉化爲字符串顯示 */ private static String byte2String(byte[] bytes) throws Exception{ return new String(bytes,"utf-8"); }