用java写一个rsa加密算法
时间: 2023-11-08 17:00:04 浏览: 111
RSA加密算法是一种非对称加密算法,它可以用于数据加密和数字签名。下面是一个Java实现的RSA加密算法示例:
```java
import java.math.BigInteger;
import java.security.SecureRandom;
public class RSA {
private BigInteger modulus;
private BigInteger privateKey;
private BigInteger publicKey;
public RSA(int bitLength) {
SecureRandom random = new SecureRandom();
BigInteger p = new BigInteger(bitLength / 2, 100, random);
BigInteger q = new BigInteger(bitLength / 2, 100, random);
modulus = p.multiply(q);
BigInteger phi = (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE));
publicKey = new BigInteger("65537");
privateKey = publicKey.modInverse(phi);
}
public byte[] encrypt(byte[] message) {
BigInteger m = new BigInteger(message);
BigInteger c = m.modPow(publicKey, modulus);
return c.toByteArray();
}
public byte[] decrypt(byte[] message) {
BigInteger c = new BigInteger(message);
BigInteger m = c.modPow(privateKey, modulus);
return m.toByteArray();
}
public static void main(String[] args) {
RSA rsa = new RSA(1024);
String message = "Hello, World!";
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));
}
}
```
在示例代码中,我们定义了一个RSA类,它包含了生成密钥对、加密和解密方法。在构造函数中,我们使用SecureRandom类生成两个素数p和q,并计算出模数和欧拉函数的值。接着,我们选择公钥的值为65537,并计算出私钥的值。在加密和解密方法中,我们使用BigInteger类来进行大数操作,调用modPow方法来进行RSA加密和解密。最后,我们在main方法中测试了加密和解密的功能。
阅读全文
相关推荐















