用Java语言设计并实现RSA加密解密程序,利用实现的RSA加密解密程序对文本加密和解密
时间: 2024-01-22 11:20:33 浏览: 26
以下是Java语言实现RSA加密解密程序的代码:
```java
import java.math.BigInteger;
import java.security.SecureRandom;
public class RSA {
private BigInteger n, d, e;
public RSA(int bitlen) {
SecureRandom r = new SecureRandom();
BigInteger p = new BigInteger(bitlen / 2, 100, r);
BigInteger q = new BigInteger(bitlen / 2, 100, r);
n = p.multiply(q);
BigInteger m = (p.subtract(BigInteger.ONE))
.multiply(q.subtract(BigInteger.ONE));
e = new BigInteger("3");
while (m.gcd(e).intValue() > 1) {
e = e.add(new BigInteger("2"));
}
d = e.modInverse(m);
}
public BigInteger encrypt(BigInteger message) {
return message.modPow(e, n);
}
public BigInteger decrypt(BigInteger message) {
return message.modPow(d, n);
}
public static void main(String[] args) {
RSA rsa = new RSA(1024);
BigInteger message = new BigInteger("123456789");
BigInteger encrypted = rsa.encrypt(message);
BigInteger decrypted = rsa.decrypt(encrypted);
System.out.println("Original message: " + message);
System.out.println("Encrypted message: " + encrypted);
System.out.println("Decrypted message: " + decrypted);
}
}
```
该程序使用了Java的BigInteger类来处理大数运算。在构造函数中,随机生成两个大素数p和q,并计算n和m。然后选择一个小于m的整数e作为加密密钥,计算d作为解密密钥。encrypt和decrypt方法分别实现了RSA的加密和解密算法。在main方法中,使用生成的密钥对一个数字进行加密和解密,并输出结果。
要使用该程序对文本进行加密和解密,可以将文本转换为BigInteger类型,然后调用encrypt和decrypt方法。以下是一个简单的示例:
```java
import java.math.BigInteger;
public class RSAExample {
public static void main(String[] args) {
RSA rsa = new RSA(1024);
String message = "Hello, world!";
BigInteger plaintext = new BigInteger(message.getBytes());
BigInteger encrypted = rsa.encrypt(plaintext);
BigInteger decrypted = rsa.decrypt(encrypted);
System.out.println("Original message: " + message);
System.out.println("Encrypted message: " + encrypted);
System.out.println("Decrypted message: " + new String(decrypted.toByteArray()));
}
}
```
该程序将字符串"Hello, world!"转换为字节数组,然后将其转换为BigInteger类型并加密。解密后再将结果转换为字节数组,最终转换为字符串输出。