1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
| import cn.hutool.crypto.SecureUtil; import cn.hutool.crypto.asymmetric.KeyType; import cn.hutool.crypto.asymmetric.RSA; import sun.misc.BASE64Encoder;
import java.security.KeyPair; import java.security.PrivateKey; import java.security.PublicKey; import java.util.HashMap; import java.util.Map;
public class RsaUtils {
public static final String ENCRYPT_TYPE = "RSA";
private static final String PUBLIC_KEY = "RSAPublicKey";
private static final String PRIVATE_KEY = "RSAPrivateKey";
public static String encrypt(String content, PublicKey publicKey) { try{ RSA rsa = new RSA(null,publicKey); return rsa.encryptBase64(content, KeyType.PublicKey); }catch (Exception e){ e.printStackTrace(); } return null; }
public static String encrypt(String content, String publicKey) { try{ RSA rsa = new RSA(null,publicKey); return rsa.encryptBase64(content, KeyType.PublicKey); }catch (Exception e){ e.printStackTrace(); } return null; }
public static String decrypt(String content, PrivateKey privateKey) { try { RSA rsa = new RSA(privateKey,null); return rsa.decryptStr(content, KeyType.PrivateKey); } catch (Exception e){ e.printStackTrace(); } return null; }
public static String decrypt(String content, String privateKey) { try { RSA rsa = new RSA(privateKey,null); return rsa.decryptStr(content, KeyType.PrivateKey); } catch (Exception e){ e.printStackTrace(); } return null; }
public static Map<String,String> generateKeyPair() { try { KeyPair pair = SecureUtil.generateKeyPair(ENCRYPT_TYPE); PrivateKey privateKey = pair.getPrivate(); PublicKey publicKey = pair.getPublic(); byte[] pubEncBytes = publicKey.getEncoded(); byte[] priEncBytes = privateKey.getEncoded();
String pubEncBase64 = new BASE64Encoder().encode(pubEncBytes); String priEncBase64 = new BASE64Encoder().encode(priEncBytes);
Map<String, String> map = new HashMap<String, String>(2); map.put(PUBLIC_KEY,pubEncBase64); map.put(PRIVATE_KEY,priEncBase64);
return map; } catch (Exception e){ e.printStackTrace(); } return null; }
}
|