今天在拉钩教育专栏《计算机网络通关29讲》上看的
// --- 私钥加密,公钥解密 ---
KeyPairGenerator rsa = KeyPairGenerator.getInstance("RSA");
KeyPair pair = rsa.generateKeyPair();
byte[] encodedKey = pair.getPrivate().getEncoded();
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encodedKey);
PrivateKey pkey = keyFactory.generatePrivate(keySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, pkey);
String str = "hello";
byte[] encodedBytes = cipher.doFinal(str.getBytes(StandardCharsets.UTF_8));
byte[] publicKey = pair.getPublic().getEncoded();
X509EncodedKeySpec keySpec1 = new X509EncodedKeySpec(publicKey);
PublicKey pubKey = keyFactory.generatePublic(keySpec1);
Cipher cipher1 = Cipher.getInstance(keyFactory.getAlgorithm());
cipher1.init(Cipher.DECRYPT_MODE, pubKey);
byte[] hello = cipher1.doFinal(encodedBytes);
System.out.println(new String(hello));
// --- 对称加解密 ---
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(128);
SecretKey key = keyGen.generateKey();
Cipher cipher2 = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] ivBytes = "1111111111111111".getBytes();
cipher2.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(ivBytes));
byte[] out2 = cipher2.doFinal("woqiao!".getBytes());
Cipher cipher21 = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher21.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(ivBytes));
byte[] woqiao = cipher21.doFinal(out2);
System.out.println(new String(woqiao));