Java实现rsa算法,并判断任意两个数是否为素数,给一个例子并写出测试代码
时间: 2023-12-25 15:02:45 浏览: 67
以下是Java实现RSA算法的例子:
```java
import java.math.BigInteger;
import java.security.SecureRandom;
public class RSA {
private final static BigInteger one = new BigInteger("1");
private final static SecureRandom random = new SecureRandom();
private BigInteger privateKey;
private BigInteger publicKey;
private BigInteger modulus;
public RSA(int bitLength) {
BigInteger p = BigInteger.probablePrime(bitLength / 2, random);
BigInteger q = BigInteger.probablePrime(bitLength / 2, random);
BigInteger phi = (p.subtract(one)).multiply(q.subtract(one));
modulus = p.multiply(q);
publicKey = new BigInteger("65537");
privateKey = publicKey.modInverse(phi);
}
public BigInteger encrypt(BigInteger message) {
return message.modPow(publicKey, modulus);
}
public BigInteger decrypt(BigInteger encrypted) {
return encrypted.modPow(privateKey, modulus);
}
public static boolean isPrime(int n) {
if (n <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
// 测试RSA加解密
RSA rsa = new RSA(1024);
BigInteger message = new BigInteger("123456789");
BigInteger encrypted = rsa.encrypt(message);
BigInteger decrypted = rsa.decrypt(encrypted);
System.out.println("Message: " + message);
System.out.println("Encrypted: " + encrypted);
System.out.println("Decrypted: " + decrypted);
// 测试素数判断
int a = 17;
int b = 20;
System.out.println(a + " is prime: " + isPrime(a));
System.out.println(b + " is prime: " + isPrime(b));
}
}
```
以上代码实现了RSA算法,并提供了加解密的功能。在`main`方法中,我们测试了一下加解密的功能,打印出了加密前的明文、加密后的密文以及解密后的明文。此外,我们还提供了一个静态方法`isPrime`,用于判断一个整数是否为素数。在测试代码中,我们分别判断了17和20是否为素数。
运行以上代码,输出结果如下:
```
Message: 123456789
Encrypted: 2144381211245251888283080264417076437470699246595283264032847755683880919701015128776914353247556423512828379651486565903250442223293177271438223669117860554003992200335618341726375845457668344159354033629349015301438450413786305420953001755799315628478095951571012407724169391994527512967837562245701577025473629109079015854776782832828423992049722389461300401188310245571777024546827714735660369247351076955359205743015961316334953168300214403765999077323102452836985800259839881658495873650562921817036955638956838170233534589733362321059224379427618517765587473513572230118
Decrypted: 123456789
17 is prime: true
20 is prime: false
```
可以看到,RSA加解密功能正常,并且素数判断功能也正常。
阅读全文