import cn.hutool.crypto.asymmetric.KeyType; import cn.hutool.crypto.asymmetric.RSA; /** * RAS非对称加密 */ public class RsaUtil { private static final String publicKey; private static final String privateKey; private static final RSA rsa; private static final String SALT = "123"; static { publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC2xhZ9YP2GhO1jxb8a1aPP7i6ZjfjD6kTS++9/HfFb9KhUGt1zr3m5H7WQ" + "/8oNUaJqaDHpjmKQ5hFUpHYVGQWjBlM+P1Ut2Y8EzKu6Kjra1tRC1r3YhoI7erLhRuv+8TZd+yswmn0ZnCskK6bUaFKlzXRaiZGzQKYQdDPJ12hubwIDAQAB"; privateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBALbGFn1g/YaE7WPFvxrVo8/uLpmN+MPqRNL7738d8Vv0qFQa3XOvebkftZD/yg1RompoMemOYpDmEVSkdhUZBaMGUz4/VS3ZjwTMq7oqOtrW1ELWvdiGgjt6suFG6/7xNl37KzCafRmcKyQrptRoUqXNdFqJkbNAphB0M8nXaG5vAgMBAAECgYBG4buHFD4+FP8bWm0qsv+8e9qGopB/KjNWv226Fpqr1s4RD/oiC0Nhj/KSMSDi2W3rZk01DosbNp4x/TXuKK4OSwwSodnhI4rVcxnuyY3leinqbHwGuVp9sSFqWsHFuY1NEFFMWTAR7aagBGCl3PU6tywoK1Fz+RKPVJQRjl+AAQJBAOgXEEF8KKEarFxjwKgmrJ3oLIBh9Wgn2+zj23DzJW2f5UXUcdNGSDZ4ANXqtiezmFDI3BPVd3dI7+Xp/5Q5Zm8CQQDJmmZq/K/VJBQg1hjmHGjNhCysg3/ztuNDr1Hw7K1nWsa7o/lA7Lv8dTI2OMBm3YE8IykhwWXSzmrbxWrVBXgBAkBy3+eF4iRiCUfCuwUCtZG+3soYCWRkV0Y9rFJTR6YA6qGavJpSTnkzrJYNS405fWUopyJ3FrN48Tr8e6OrA/Y1AkEApxHsREdJ1AGFKL0kfzYV6BLcDs8fLzJl3kahSl5pSZihzwiRXCuTkiDxTpvzXou8OMEOqimin3NufNh6szRIAQJBALBUohflpAKIeazX/+eT1cmGv8smGG4rcqWMXAesUIminNw/lUP55v2AIeIe+uZc2+h4p/VbAYjIQWmMP9Ngdjg="; rsa = new RSA(privateKey, publicKey); } /** * 公钥加密 * @param data 加密前数据 * @return 返回加密后数据, base64格式 */ public static String encrypt(String data) { return rsa.encryptBase64(data + SALT, KeyType.PublicKey); } /** * 私钥解密 * @param encryptStr 加密后的字符串 * @return */ public static String decrypt(String encryptStr) { return rsa.decryptStr(encryptStr, KeyType.PrivateKey); } public static void main(String[] args) { System.out.println("公钥:" + publicKey); System.out.println("私钥:" + privateKey); String encryptStr = encrypt("test"); String decryptStr = decrypt(encryptStr); System.out.println("加密后:" + encryptStr); System.out.println("解密后:" + decryptStr); } }
依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
</dependency>