04_RSA非对称加密
程序员文章站
2024-03-14 14:20:52
...
/**
* <p>Description: RSA 非对称加密</p>
*
* @author XXX
* @date 2020/12/14 21:33
* @since JDK1.8
*/
public class RSADemo {
private static Base64.Encoder encoder = Base64.getEncoder();
private static Base64.Decoder decoder = Base64.getDecoder();
private static final String RSA = "RSA";
public static void main(String[] args) throws Exception {
//创建秘钥对
//KeyPairGenerator 秘钥对生成器对象
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RSA);
//生成秘钥对
KeyPair keyPair = keyPairGenerator.generateKeyPair();
//生成公钥
PrivateKey privateKey = keyPair.getPrivate();
//生成私钥
PublicKey publicKey = keyPair.getPublic();
//获取字节数组
byte[] privateKeyEncoded = privateKey.getEncoded();
byte[] publicKeyEncoded = publicKey.getEncoded();
String privateKeyString = new String(encoder.encode(privateKeyEncoded));
String publicKeyString = new String(encoder.encode(publicKeyEncoded));
// System.out.println("privateKeyString-----------" + privateKeyString);
// System.out.println("publicKeyString-----------" + publicKeyString);
Cipher cipher = Cipher.getInstance(RSA);
//使用私钥进行加密
cipher.init(Cipher.ENCRYPT_MODE,privateKey);
byte[] bytes = cipher.doFinal("哈哈".getBytes());
String encrypt = new String(encoder.encode(bytes));
System.out.println(encrypt);
//使用公钥解密
cipher.init(Cipher.DECRYPT_MODE,publicKey);
byte[] decrypt = cipher.doFinal(bytes);
System.out.println(new String(decrypt));
//根据**对生成Key
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(decoder.decode(privateKeyString));
PrivateKey privateKey2 = keyFactory.generatePrivate(privateKeySpec);
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(decoder.decode(publicKeyString));
PublicKey publicKey2 = keyFactory.generatePublic(publicKeySpec);
//加密模式和填充模式 默认 RSA/ECB/PKCS5Padding
Cipher c = Cipher.getInstance("RSA/CBC/PKCS5Padding");
//CBC的情况下, 加密需要iv向量 key.getBytes()
IvParameterSpec iv = new IvParameterSpec("key".getBytes());
SecretKeySpec keySpec = new SecretKeySpec("key".getBytes(), "DES");
c.init(Cipher.ENCRYPT_MODE, keySpec, iv);
//解密也需要向量
cipher.init(Cipher.DECRYPT_MODE, keySpec,iv);
}
}
上一篇: gRPC 初识
下一篇: SM4国密加密解密实现代码demo