用Java编写RSA加密算法
时间: 2024-05-05 22:21:06 浏览: 256
java编写加密算法RSA
RSA加密算法是一种非对称加密算法,可以用于数据的加密和解密。下面是用Java语言实现RSA加密算法的代码示例:
```java
import java.math.BigInteger;
import java.security.SecureRandom;
public class RSA {
private BigInteger n, d, e;
private int bitlen = 1024;
public RSA() {
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 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 text1 = "Hello World";
System.out.println("Plaintext: " + text1);
BigInteger plaintext = new BigInteger(text1.getBytes());
BigInteger ciphertext = rsa.encrypt(plaintext);
System.out.println("Ciphertext: " + ciphertext);
BigInteger deciphertext = rsa.decrypt(ciphertext);
System.out.println("Deciphertext: " + new String(deciphertext.toByteArray()));
}
public synchronized BigInteger encrypt(BigInteger message) {
return message.modPow(e, n);
}
public synchronized BigInteger decrypt(BigInteger message) {
return message.modPow(d, n);
}
}
```
上述代码中,我们定义了一个RSA类,该类包含了RSA加密算法的实现。构造方法中,我们生成了一个1024位的RSA密钥对,其中包含了公钥e、私钥d以及模数n。encrypt()方法用于加密数据,decrypt()方法用于解密数据。我们还提供了一个简单的main()方法,用于测试加密和解密功能。
阅读全文