帮我用java写RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING 加密、解密
时间: 2024-01-17 22:04:31 浏览: 132
RSA+ECB+OAEPWithSHA-256AndMGF1Padding
好的,我能够帮你用 Java 写 RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING 加密和解密。以下是示例代码:
加密:
```java
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.OAEPParameterSpec;
import javax.crypto.spec.PSource;
import java.security.*;
import java.security.spec.MGF1ParameterSpec;
import java.security.spec.X509EncodedKeySpec;
public class Encryptor {
public static byte[] encrypt(byte[] input, PublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING");
MGF1ParameterSpec mgf1ParameterSpec = new MGF1ParameterSpec("SHA-256");
OAEPParameterSpec oaepParameterSpec = new OAEPParameterSpec("SHA-256", "MGF1", mgf1ParameterSpec, PSource.PSpecified.DEFAULT);
cipher.init(Cipher.ENCRYPT_MODE, publicKey, oaepParameterSpec);
return cipher.doFinal(input);
}
}
```
解密:
```java
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.OAEPParameterSpec;
import javax.crypto.spec.PSource;
import java.security.*;
import java.security.spec.MGF1ParameterSpec;
import java.security.spec.PKCS8EncodedKeySpec;
public class Decryptor {
public static byte[] decrypt(byte[] input, PrivateKey privateKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING");
MGF1ParameterSpec mgf1ParameterSpec = new MGF1ParameterSpec("SHA-256");
OAEPParameterSpec oaepParameterSpec = new OAEPParameterSpec("SHA-256", "MGF1", mgf1ParameterSpec, PSource.PSpecified.DEFAULT);
cipher.init(Cipher.DECRYPT_MODE, privateKey, oaepParameterSpec);
return cipher.doFinal(input);
}
}
```
你需要提供公钥和私钥。下面是使用示例:
```java
import java.security.*;
public class Main {
public static void main(String[] args) throws Exception {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
String plainText = "Hello, world!";
byte[] encrypted = Encryptor.encrypt(plainText.getBytes(), publicKey);
byte[] decrypted = Decryptor.decrypt(encrypted, privateKey);
String decryptedText = new String(decrypted);
System.out.println("Original text: " + plainText);
System.out.println("Decrypted text: " + decryptedText);
}
}
```
在这里,我们首先生成一个 RSA 密钥对,并将公钥和私钥传递给加密和解密函数。然后我们加密字符串 "Hello, world!",并使用相同的私钥解密它。最后,我们将原始文本和解密后的文本一起打印出来。
提醒:在真实的应用中,你需要将生成的密钥保存到文件或数据库中,以便以后使用。
阅读全文