区别:
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); } }
运行结果:
原文地址:https://www.cnblogs.com/lsy131479/p/9038003.html
时间: 2024-10-25 06:43:21