標籤:news bytes 個人觀點 ase word print 技術分享 java data
區別:
MD5加密:
加密時通過原字串加密成另一串字串
解密時需要原加密字串進行重新加密比較兩次加密結果是否一致
T=RSA加密:
加密時通過原字串產生金鑰組(公開金鑰+私密金鑰)
解密時通過公開金鑰和私密金鑰進行解密,解密出原字串進行比較是否一致
個人觀點:
RSA加密略比MD5加密牛逼一點點
但凡事都有好壞 MD5加密執行效率比RSA慢
廢話不多說上栗子:
MD5加密:
package cn.news.util;import java.security.MessageDigest;/** * * @author: 房上的貓 * * @time: 2018年5月14日 下午8:04:44 * * @部落格地址: https://www.cnblogs.com/lsy131479/ * */public class MD5 { private static String MD(String s) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(s.getBytes("utf-8")); byte[] bytes = md.digest(s.getBytes("utf-8")); return toHex(bytes); } catch (Exception e) { throw new RuntimeException(e); } } private static String toHex(byte[] bytes) { final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray(); StringBuilder ret = new StringBuilder(bytes.length * 2); for (int i = 0; i < bytes.length; i++) { ret.append(HEX_DIGITS[(bytes[i] >> 4) & 0x0f]); ret.append(HEX_DIGITS[bytes[i] & 0x0f]); } return ret.toString(); } public static void main(String[] args) { System.out.println(MD("hello word")); }}
結果:
RSA加密與解密:
package cn.news.util;import java.security.KeyPair;import java.security.KeyPairGenerator;import java.security.PrivateKey;import java.security.PublicKey;import java.util.Base64;import javax.crypto.Cipher;/** * * @author: 房上的貓 * * @time: 2018年5月14日 下午7:56:12 * * @部落格地址: https://www.cnblogs.com/lsy131479/ * */public class RSA { public static String data = "hello world"; public static void main(String[] args) throws Exception { // TODO Auto-generated method stub KeyPair keyPair = genKeyPair(1024); // 擷取公開金鑰,並以base64格式列印出來 PublicKey publicKey = keyPair.getPublic(); System.out.println("公開金鑰:" + new String(Base64.getEncoder().encode(publicKey.getEncoded()))); // 擷取私密金鑰,並以base64格式列印出來 PrivateKey privateKey = keyPair.getPrivate(); System.out.println("私密金鑰:" + new String(Base64.getEncoder().encode(privateKey.getEncoded()))); // 公開金鑰加密 byte[] encryptedBytes = encrypt(data.getBytes(), publicKey); System.out.println("加密後:" + new String(encryptedBytes)); // 私密金鑰解密 byte[] decryptedBytes = decrypt(encryptedBytes, privateKey); System.out.println("解密後:" + new String(decryptedBytes)); } // 產生金鑰組 public static KeyPair genKeyPair(int keyLength) throws Exception { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(1024); return keyPairGenerator.generateKeyPair(); } // 公開金鑰加密 public static byte[] encrypt(byte[] content, PublicKey publicKey) throws Exception { Cipher cipher = Cipher.getInstance("RSA");// java預設"RSA"="RSA/ECB/PKCS1Padding" cipher.init(Cipher.ENCRYPT_MODE, publicKey); return cipher.doFinal(content); } // 私密金鑰解密 public static byte[] decrypt(byte[] content, PrivateKey privateKey) throws Exception { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, privateKey); return cipher.doFinal(content); }}
運行結果:
Java MD5加密與RSA加密