用java写一个RSA加密算法
时间: 2023-05-27 14:05:21 浏览: 53
由于RSA算法涉及到大数运算,这里给出一个简单的实现,使用了BigInteger类。
import java.math.BigInteger;
import java.security.SecureRandom;
public class RSA {
private BigInteger p;
private BigInteger q;
private BigInteger n;
private BigInteger phi;
private BigInteger e;
private BigInteger d;
private int bitlength = 1024;
private SecureRandom r;
public RSA() {
r = new SecureRandom();
p = BigInteger.probablePrime(bitlength, r);
q = BigInteger.probablePrime(bitlength, r);
n = p.multiply(q);
phi = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
e = BigInteger.probablePrime(bitlength / 2, r);
while (phi.gcd(e).compareTo(BigInteger.ONE) > 0 && e.compareTo(phi) < 0) {
e.add(BigInteger.ONE);
}
d = e.modInverse(phi);
}
public RSA(BigInteger e, BigInteger d, BigInteger n) {
this.e = e;
this.d = d;
this.n = n;
}
public static void main(String[] args) {
RSA rsa = new RSA();
String message = "This is a test message.";
byte[] encrypted = rsa.encrypt(message.getBytes());
byte[] decrypted = rsa.decrypt(encrypted);
System.out.println("Original message: " + message);
System.out.println("Encrypted message: " + new String(encrypted));
System.out.println("Decrypted message: " + new String(decrypted));
}
public byte[] encrypt(byte[] message) {
return (new BigInteger(message)).modPow(e, n).toByteArray();
}
public byte[] decrypt(byte[] message) {
return (new BigInteger(message)).modPow(d, n).toByteArray();
}
}
在main方法中,我们创建一个RSA实例,然后使用它的encrypt方法加密字符串,再使用decrypt方法解密得到原始字符串。注意,加密后的byte数组可能包含负数,因此在转换为字符串时需要使用new String(byte[], Charset)方法传入字符集,否则可能会出现乱码。