麻烦写一段RSA加密PKCS1 JAVA代码
时间: 2023-07-10 13:08:47 浏览: 53
好的,以下是一个使用RSA加密PKCS1的JAVA代码示例,其中使用了Bouncy Castle库:
```java
import org.bouncycastle.crypto.AsymmetricBlockCipher;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.engines.RSAEngine;
import org.bouncycastle.crypto.params.AsymmetricKeyParameter;
import org.bouncycastle.crypto.params.RSAKeyParameters;
import org.bouncycastle.crypto.util.PublicKeyFactory;
import org.bouncycastle.crypto.util.PrivateKeyFactory;
import org.bouncycastle.crypto.util.PKCS1Encoding;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import java.security.Security;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.interfaces.RSAPublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
public class RSAPKCS1Example {
public static void main(String[] args) throws Exception {
Security.addProvider(new BouncyCastleProvider());
// 生成RSA密钥对
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");
keyPairGenerator.initialize(2048, new SecureRandom());
KeyPair keyPair = keyPairGenerator.generateKeyPair();
// 获取公钥和私钥
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
// 加密数据
byte[] data = "Hello, World!".getBytes("UTF-8");
byte[] encryptedData = encrypt(data, publicKey);
// 解密数据
byte[] decryptedData = decrypt(encryptedData, privateKey);
String decryptedText = new String(decryptedData, "UTF-8");
// 输出结果
System.out.println("原始数据:" + new String(data, "UTF-8"));
System.out.println("加密后数据:" + bytesToHex(encryptedData));
System.out.println("解密后数据:" + decryptedText);
}
public static byte[] encrypt(byte[] data, RSAPublicKey publicKey) throws Exception {
AsymmetricKeyParameter keyParameters = PublicKeyFactory.createKey(publicKey.getEncoded());
AsymmetricBlockCipher cipher = new PKCS1Encoding(new RSAEngine());
cipher.init(true, keyParameters);
return cipher.processBlock(data, 0, data.length);
}
public static byte[] decrypt(byte[] encryptedData, RSAPrivateKey privateKey) throws Exception {
AsymmetricKeyParameter keyParameters = PrivateKeyFactory.createKey(privateKey.getEncoded());
AsymmetricBlockCipher cipher = new PKCS1Encoding(new RSAEngine());
cipher.init(false, keyParameters);
return cipher.processBlock(encryptedData, 0, encryptedData.length);
}
public static String bytesToHex(byte[] data) {
StringBuilder builder = new StringBuilder();
for (byte b : data) {
builder.append(String.format("%02X", b));
}
return builder.toString();
}
}
```
在上面的示例中,我们使用了Bouncy Castle库来进行RSA加密和解密,并使用了PKCS1编码方式。首先,我们使用`KeyPairGenerator`生成一个2048位的RSA密钥对,并从中获取公钥和私钥。然后,我们将原始数据进行加密,并将加密后的数据存储在`encryptedData`数组中。最后,我们使用私钥对加密后的数据进行解密,并将解密后的数据存储在`decryptedData`数组中。注意,我们使用了一个辅助函数`bytesToHex`将字节数组转换为十六进制字符串,以便于输出结果。