密码学RSA算法java
时间: 2023-11-10 12:58:35 浏览: 36
以下是Java实现RSA算法的示例代码:
```java
import java.math.BigInteger;
import java.security.SecureRandom;
public class RSA {
private BigInteger modulus;
private BigInteger privateKey;
private BigInteger publicKey;
// 初始化RSA算法
public RSA(int bitLength) {
SecureRandom random = new SecureRandom();
BigInteger p = BigInteger.probablePrime(bitLength / 2, random);
BigInteger q = BigInteger.probablePrime(bitLength / 2, random);
BigInteger phi = (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE));
this.modulus = p.multiply(q);
this.publicKey = new BigInteger("65537"); // 一般取65537
this.privateKey = this.publicKey.modInverse(phi);
}
// 加密明文
public BigInteger encrypt(BigInteger plaintext) {
return plaintext.modPow(publicKey, modulus);
}
// 解密密文
public BigInteger decrypt(BigInteger ciphertext) {
return ciphertext.modPow(privateKey, modulus);
}
public static void main(String[] args) {
RSA rsa = new RSA(1024);
BigInteger plaintext = new BigInteger("123456");
System.out.println("明文:" + plaintext);
BigInteger ciphertext = rsa.encrypt(plaintext);
System.out.println("密文:" + ciphertext);
BigInteger decryptedText = rsa.decrypt(ciphertext);
System.out.println("解密后的明文:" + decryptedText);
}
}
```
在上述代码中,我们首先生成了一个RSA对象,并指定了密钥长度为1024位。接着,我们可以使用encrypt方法对明文进行加密,使用decrypt方法对密文进行解密。最后,我们在main方法中对一个简单的明文进行加密、解密并输出结果。
需要注意的是,RSA算法是一种公钥加密算法,因此我们只需要保护好私钥即可,公钥可以公开,不需要保密。在实际应用中,我们可以将公钥告知通信对方,让对方使用公钥对数据进行加密,然后再使用私钥进行解密。这样可以保证数据的安全性。