java 如何生成rsa OAEPW填充模式得密钥 并保存 每次使用同一套进行加密解密
时间: 2024-04-23 08:26:57 浏览: 187
Java 生成RSA密钥进行数据加密解密 支持超长字符分区
在Java中,可以使用Java Cryptography Architecture(JCA)提供的API来生成RSA密钥对并进行加密解密。下面是使用JCA生成RSA密钥对并进行加密解密并保存的示例代码:
```java
import javax.crypto.Cipher;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.*;
public class RSAExample {
private static final String ALGORITHM = "RSA";
private static final String TRANSFORMATION = "RSA/ECB/OAEPWithSHA-256AndMGF1Padding";
private static final int KEY_SIZE = 2048;
private static final String PRIVATE_KEY_FILE = "private.key";
private static final String PUBLIC_KEY_FILE = "public.key";
public static void main(String[] args) throws Exception {
// 生成密钥对
KeyPair keyPair = generateKeyPair();
// 明文
String plainText = "Hello, world!";
// 加密
byte[] cipherText = encrypt(plainText.getBytes(), keyPair.getPublic());
// 解密
byte[] decryptedText = decrypt(cipherText, keyPair.getPrivate());
// 输出结果
System.out.println("Plain text: " + plainText);
System.out.println("Cipher text: " + new String(cipherText));
System.out.println("Decrypted text: " + new String(decryptedText));
}
// 生成密钥对并保存到文件
public static KeyPair generateKeyPair() throws Exception {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);
keyPairGenerator.initialize(KEY_SIZE);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
saveToFile(PRIVATE_KEY_FILE, keyPair.getPrivate().getEncoded());
saveToFile(PUBLIC_KEY_FILE, keyPair.getPublic().getEncoded());
return keyPair;
}
// 从文件中加载私钥
public static PrivateKey loadPrivateKey() throws Exception {
byte[] privateKeyBytes = Files.readAllBytes(Paths.get(PRIVATE_KEY_FILE));
PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
return keyFactory.generatePrivate(privateKeySpec);
}
// 从文件中加载公钥
public static PublicKey loadPublicKey() throws Exception {
byte[] publicKeyBytes = Files.readAllBytes(Paths.get(PUBLIC_KEY_FILE));
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
return keyFactory.generatePublic(publicKeySpec);
}
// 加密
public static byte[] encrypt(byte[] data, PublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(data);
}
// 解密
public static byte[] decrypt(byte[] data, PrivateKey privateKey) throws Exception {
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(data);
}
// 保存密钥到文件
public static void saveToFile(String fileName, byte[] data) throws Exception {
Files.write(Paths.get(fileName), data);
}
}
```
在上面的示例代码中,使用`generateKeyPair`方法生成RSA密钥对,并将其保存到文件中。使用`loadPrivateKey`和`loadPublicKey`方法从文件中加载私钥和公钥。使用`encrypt`和`decrypt`方法进行加密和解密。使用`saveToFile`方法将密钥保存到文件中。
需要注意的是,生成的密钥对需要妥善保管,私钥不应该泄露给他人。此外,加密和解密时需要使用相同的填充模式和密钥对。
阅读全文