密码学-RSA算法

。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是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算法是一种公钥加密算法,因此我们只需要保护好私钥即可,公钥可以公开,不需要保密。在实际应用中,我们可以将公钥告知通信对方,让对方使用公钥对数据进行加密,然后再使用私钥进行解密。这样可以保证数据的安全性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值