RSA/ECB/OAEPWithSHA-256AndMGF1Padding 实现加解密
时间: 2024-01-24 17:05:21 浏览: 213
RSA+ECB+OAEPWithSHA-256AndMGF1Padding
RSA/ECB/OAEPWithSHA-256AndMGF1Padding是一种RSA加密算法,使用OAEP(Optimal Asymmetric Encryption Padding)填充,使用SHA-256哈希函数和MGF1(Mask Generation Function 1)填充。
以下是Java代码示例:
```java
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.MGF1ParameterSpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
import javax.crypto.spec.OAEPParameterSpec;
import javax.crypto.spec.PSource;
public class RSAEncryption {
// 生成RSA密钥对
public static KeyPair generateRSAKeyPair() throws Exception {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048, new SecureRandom());
return keyPairGenerator.generateKeyPair();
}
// RSA加密
public static byte[] encryptRSA(byte[] data, PublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
OAEPParameterSpec oaepParameterSpec = new OAEPParameterSpec("SHA-256", "MGF1",
new MGF1ParameterSpec("SHA-256"), PSource.PSpecified.DEFAULT);
cipher.init(Cipher.ENCRYPT_MODE, publicKey, oaepParameterSpec);
return cipher.doFinal(data);
}
// RSA解密
public static byte[] decryptRSA(byte[] data, PrivateKey privateKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
OAEPParameterSpec oaepParameterSpec = new OAEPParameterSpec("SHA-256", "MGF1",
new MGF1ParameterSpec("SHA-256"), PSource.PSpecified.DEFAULT);
cipher.init(Cipher.DECRYPT_MODE, privateKey, oaepParameterSpec);
return cipher.doFinal(data);
}
// 测试
public static void main(String[] args) throws Exception {
// 生成RSA密钥对
KeyPair keyPair = generateRSAKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
// 加密数据
byte[] data = "Hello, RSA!".getBytes();
byte[] encryptedData = encryptRSA(data, publicKey);
// 解密数据
byte[] decryptedData = decryptRSA(encryptedData, privateKey);
// 输出结果
System.out.println("原始数据:" + new String(data));
System.out.println("加密后的数据:" + new String(encryptedData));
System.out.println("解密后的数据:" + new String(decryptedData));
}
}
```
需要注意的是,RSA加密算法不适合加密大量数据,因为加密后的数据长度会比原始数据长度长很多,而且加密速度较慢,所以一般只用于加密对称加密算法的密钥。
阅读全文