前言:
此刻姐妹们对“java非对称加密算法rsa”大约比较关怀,姐妹们都想要了解一些“java非对称加密算法rsa”的相关资讯。那么小编同时在网络上搜集了一些对于“java非对称加密算法rsa””的相关文章,希望小伙伴们能喜欢,看官们一起来学习一下吧!介绍语
本号主要是Java常用关键技术点,通用工具类的分享;以及springboot+springcloud+Mybatisplus+druid+mysql+redis+swagger+maven+docker等集成框架的技术分享;datax、kafka、flink等大数据处理框架的技术分享。文章会不断更新,欢迎码友关注点赞收藏转发!
望各位码友点击关注,冲1000粉。后面会录制一些视频教程,图文和视频结合,比如:图书介绍网站系统、抢购系统、大数据中台系统等。技术才是程序猿的最爱,码友们冲啊
如果码友觉得代码太长,可以从头到尾快速扫射一遍,了解大概即可。觉得有用后再转发收藏,以备不时之需。
正文:
前面发了一篇aes对称加密工具类,深得码友信赖,帮助我转发,非常感谢码友。今天再给出一篇rsa非对称加密工具类。在java中对称加密和非对称加密都是常用的,一般情况下对称加密用于大量数据加密,比rsa快;而rsa一般用于特别重要的小量数据加密,例如密码等可以用rsa加密,把公钥给客户端,密码使用md5加密,然后再使用公钥进行加密,最后传输到后端,后端使用私钥解密,得到密码的md5值,最后与库中密码比较,相等则登录成功,反之登录错误。
rsa的公钥私钥,一般不会每次都生成,而是生成后存储在文件中或者存储在数据库中,可多次使用。
使用例子
import com.javabage.tools.utils.RSAEncryptUtil; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.crypto.BadPaddingException; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; public class RSAEncryptUtilTest { private static final Logger logger = LoggerFactory.getLogger(RSAEncryptUtilTest.class); @Test public void rsaTest() throws NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, InvalidKeySpecException, BadPaddingException, InvalidKeyException { // 生成公钥和私钥 RSAEncryptUtil.genKeyPair(); logger.info("公钥为:{}", RSAEncryptUtil.getRSAPublicKey()); logger.info("私钥为:{}", RSAEncryptUtil.getRSAPrivateKey()); // 加密字符串,用公钥加密,用私钥解密 String message = "kd35734j74kjffy9r"; logger.info("待加密字符串:{}", message); String messageEn = RSAEncryptUtil.encrypt(message, RSAEncryptUtil.getRSAPublicKey()); logger.info("公钥加密后的字符串为:{}", messageEn); String messageDe = RSAEncryptUtil.decrypt(messageEn, RSAEncryptUtil.getRSAPrivateKey()); logger.info("私钥解密还原后的字符串为:{}", messageDe); } } // 控制台输出 23:57:58.822 [main] INFO - 公钥为:MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnm4rf1ukashv7J+mtLyOyVfK7vZxHtNxaUJxfkGnVVOrI/M5fNhHNfl6wtUi8XislP7t5/sF4zdJgLDZ4reIma8SVueaSX85Ts/bXMLBUvVk/noSzhD3Fa+qSpcgv59NlWNNJclssZFK2bRS6NOdmIIWP/V+Ld25RrKZDahxu6dPldFPgEXAhS7C3LgdoAwTsNTAqDgPYVscVStXtFCudFWyNrVhmzCHTfSRF5+CbPH+HlnmoLje+s0pY9eVA46QKCzYVstjFarnPh4TdqRb4CQ51KEFBgyaRiNSrCskbpgZDtPjSlfdjqy48UU4fei7w9PVF34e+g8PYSwS9OPX5wIDAQAB 23:57:58.823 [main] INFO - 私钥为:MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCebit/W6RqyG/sn6a0vI7JV8ru9nEe03FpQnF+QadVU6sj8zl82Ec1+XrC1SLxeKyU/u3n+wXjN0mAsNnit4iZrxJW55pJfzlOz9tcwsFS9WT+ehLOEPcVr6pKlyC/n02VY00lyWyxkUrZtFLo052YghY/9X4t3blGspkNqHG7p0+V0U+ARcCFLsLcuB2gDBOw1MCoOA9hWxxVK1e0UK50VbI2tWGbMIdN9JEXn4Js8f4eWeaguN76zSlj15UDjpAoLNhWy2MVquc+HhN2pFvgJDnUoQUGDJpGI1KsKyRumBkO0+NKV92OrLjxRTh96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uQSyDIynhiXZadhfkDr02ThZTAhG34J0+KdqDMjHHlMYCsq0chYZ8cNyES2E9UClui05WUL6tK7mzzBrUku8XsdlHAONA2YOCUdW9metjRldX9PfVXNcctFem9l3X07dV8Kv2CaF0V2GXYxWoik1QNmItVV/aP9DUCOriD2tn 23:57:58.823 [main] INFO - 待加密字符串:kd35734j74kjffy9r 23:57:59.979 [main] INFO - 公钥加密后的字符串为:kpa3L/GH0RUyGUmFojEeLfHxzs1EU2/Pn9to6JaUKqo1HH3o7jk6ETrhyblfQ5pjE5Ic20NiUJokAHN6EYjpBofR8XT9WdzPiW2cdUf9OLVazFyKm8wOzESzpfF+BTx67Sy7pQUxVJgUXasjdjAAElyCtxzV69/Tk03+gbIhoeGQELn//7fsA3wXJqMQLrXhbXT6vN4a0ya3D8UYiIyT3upWQUHlABEfmx63nXOaigvqjBTOunyuHSMSOYaNIC4bvkhWTQIaotWPvDy9Ra9lvmOwbRg/FvU/QYjYxWYEYz5EYeNCGiKG477E5eGW8xs1LVyqkPbqMsmovYgrvWk5PQ== 23:57:59.986 [main] INFO - 私钥解密还原后的字符串为:kd35734j74kjffy9r
工具类源码:
import org.apache.commons.codec.binary.Base64; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import java.nio.charset.StandardCharsets; import java.security.*; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.HashMap; import java.util.Map; /** * rsa工具类 * * @author liangxn */ public class RSAEncryptUtil { private static final Map<String, String> KEY_MAP = new HashMap<>(); private RSAEncryptUtil() { } /** * 随机生成密钥对 * * @throws NoSuchAlgorithmException */ public static void genKeyPair() throws NoSuchAlgorithmException { // 密钥生成器 KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); // 设置为2048位长度 generator.initialize(2048, new SecureRandom()); // 生成密钥对 KeyPair keyPair = generator.generateKeyPair(); // 获取私钥 RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); // 获取公钥 RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); // 进行64位编码得到公钥的字符串 String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded())); // 进行64位编码得到私钥的字符串 String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded()))); // 将公钥和私钥保存到Map KEY_MAP.put("publicKey", publicKeyString); KEY_MAP.put("privateKey", privateKeyString); } /** * RSA公钥加密 * * @param source 待加密字符串 * @param publicKey 公钥 * @return 加密后的字符串 * @throws Exception 加密过程中的异常信息 */ public static String encrypt(String source, String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { // 把字符串转成字节 byte[] decoded = Base64.decodeBase64(publicKey); RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA") .generatePublic(new X509EncodedKeySpec(decoded)); // rsa实例 Cipher cipher = Cipher.getInstance("RSA"); // 加密模式为加密,然后加密 cipher.init(Cipher.ENCRYPT_MODE, pubKey); return Base64.encodeBase64String(cipher.doFinal(source.getBytes(StandardCharsets.UTF_8))); } /** * RSA私钥解密 * * @param encText 加密字符串 * @param privateKey 私钥 * @return 解密后的字符串 * @throws Exception 解密过程中的异常信息 */ public static String decrypt(String encText, String privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { // 把字符串转成字节 byte[] inputByte = Base64.decodeBase64(encText.getBytes(StandardCharsets.UTF_8)); byte[] decoded = Base64.decodeBase64(privateKey); // 获取rsa密钥实例 RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA") .generatePrivate(new PKCS8EncodedKeySpec(decoded)); // rsa实例 Cipher cipher = Cipher.getInstance("RSA"); // 加密模式为解密,然后解密 cipher.init(Cipher.DECRYPT_MODE, priKey); return new String(cipher.doFinal(inputByte)); } public static String getRSAPrivateKey() { return KEY_MAP.get("privateKey"); } public static String getRSAPublicKey() { return KEY_MAP.get("publicKey"); } }
鄙人编码十年多,在项目中也积累了一些工具类,很多工具类在每个项目都有在用,很实用。大部分是鄙人封装的,有些工具类是同事封装的,有些工具类已经不记得是ctrl+c的还是自己封装的了,现在有空就会总结项目中大部分的工具类,分享给各位码友。如果文章中涉及的代码有侵权行为请通知鄙人处理。
计划是先把工具类整理出来,正所谓工欲善其事,必先利其器。项目中不管是普通单体项目还是多模块maven项目或是分布式微服务,一部分功能模块都是可以重用的,工具类模块就是其中之一。
标签: #java非对称加密算法rsa #rsajavac