java RSA加密算法代码
时间: 2023-11-10 13:58:09 浏览: 86
以下是Java实现RSA加密算法的代码:
```java
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import javax.crypto.Cipher;
public class RSA {
private static final int KEY_SIZE = 512;
public static void main(String[] args) throws Exception {
String plainText = "Hello, RSA!";
KeyPair keyPair = generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
byte[] encryptedText = encrypt(plainText.getBytes(), publicKey);
byte[] decryptedText = decrypt(encryptedText, privateKey);
System.out.println("Plain text: " + plainText);
System.out.println("Encrypted text: " + new String(encryptedText));
System.out.println("Decrypted text: " + new String(decryptedText));
}
public static KeyPair generateKeyPair() throws Exception {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(KEY_SIZE);
return keyPairGenerator.generateKeyPair();
}
public static byte[] encrypt(byte[] input, PublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(input);
}
public static byte[] decrypt(byte[] input, PrivateKey privateKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(input);
}
public static PublicKey getPublicKey(byte[] modulusBytes, byte[] exponentBytes) throws Exception {
BigInteger modulus = new BigInteger(1, modulusBytes);
BigInteger exponent = new BigInteger(1, exponentBytes);
RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus, exponent);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return keyFactory.generatePublic(spec);
}
public static PrivateKey getPrivateKey(byte[] modulusBytes, byte[] exponentBytes, byte[] dBytes, byte[] pBytes, byte[] qBytes) throws Exception {
BigInteger modulus = new BigInteger(1, modulusBytes);
BigInteger exponent = new BigInteger(1, exponentBytes);
BigInteger d = new BigInteger(1, dBytes);
BigInteger p = new BigInteger(1, pBytes);
BigInteger q = new BigInteger(1, qBytes);
RSAPrivateKeySpec spec = new RSAPrivateKeySpec(modulus, exponent);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(spec);
RSAPrivateCrtKeySpec crtSpec = new RSAPrivateCrtKeySpec(modulus, exponent, d, p, q, null, null, null);
return keyFactory.generatePrivate(crtSpec);
}
}
```
在main方法中,我们首先生成了一个密钥对(公钥和私钥),然后使用公钥加密了一段明文,再使用私钥解密得到了原文。其中,使用了Java内置的RSA加密算法实现,通过调用Cipher类的init和doFinal方法实现加解密。同时,我们还提供了getPublicKey和getPrivateKey方法,用于根据给定的参数构造PublicKey和PrivateKey对象。
阅读全文