刘勇虎的官方网站
网站内容包含大前端、服务器开发、Python开发、iOS开发、Android开发、网站维护等技术文章。专注于分享技术经验,职业心得体会,IT优秀文章与教程创作。
Stay hungry,Stay foolish,Stay young
private static final String KEY_ALGORITHM = "RSA";
private static final String PUBLIC_KEY ="publicKey";
private static final String PRIVATE_KEY ="privateKey";
public static void main(String[] args) throws Exception{
Map<String,String> keyMap = genKey();
RSAPublicKey publicKey = getPublicKey(keyMap.get(PUBLIC_KEY));
RSAPrivateKey privateKey = getPrivateKey(keyMap.get(PRIVATE_KEY));
String info ="明文123456";
//加密
byte[] bytes = encrypt(info.getBytes("utf-8"),publicKey);
//解密
bytes = decrypt(bytes, privateKey);
System.out.println(new String(bytes,"utf-8"));
}
public static Map<String,String> genKey() throws NoSuchAlgorithmException{
Map<String,String> keyMap = new HashMap<String,String>();
KeyPairGenerator keygen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
SecureRandom random = new SecureRandom();
// random.setSeed(keyInfo.getBytes());
// 初始加密,512位已被破解,用1024位,最好用2048位
keygen.initialize(1024, random);
// 取得密钥对
KeyPair kp = keygen.generateKeyPair();
RSAPrivateKey privateKey = (RSAPrivateKey)kp.getPrivate();
String privateKeyString = Base64.encode(privateKey.getEncoded());
RSAPublicKey publicKey = (RSAPublicKey)kp.getPublic();
String publicKeyString = Base64.encode(publicKey.getEncoded());
keyMap.put(PUBLIC_KEY, publicKeyString);
keyMap.put(PRIVATE_KEY, privateKeyString);
return keyMap;
}
public static RSAPublicKey getPublicKey(String publicKey) throws Exception{
byte[] keyBytes = LBase64.decode(publicKey);
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
return (RSAPublicKey) keyFactory.generatePublic(spec);
}
public static RSAPrivateKey getPrivateKey(String privateKey) throws Exception{
byte[] keyBytes = LBase64.decode(privateKey);
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
return (RSAPrivateKey) keyFactory.generatePrivate(spec);
}
转载自
https://blog.csdn.net/mafei852213034/article/details/53319908?locationNum=10&fps=1