利用RSA算法加解密学号,JAVA代码实现
时间: 2023-12-01 21:54:27 浏览: 98
好的,接下来是利用RSA算法加解密学号的JAVA代码实现。
请先确保你已经安装了Java环境,并且导入了Bouncy Castle加密库。如果还没有安装和导入,可以自行在网上搜索教程。
1. 加密学号
```java
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.interfaces.RSAPublicKey;
import javax.crypto.Cipher;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class RSAEncrypt {
public static void main(String[] args) {
try {
String studentId = "1234567890"; // 待加密的学号
byte[] plainText = studentId.getBytes();
// 初始化加密环境
Security.addProvider(new BouncyCastleProvider());
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "BC");
kpg.initialize(4096, new SecureRandom());
// 生成RSA密钥对
KeyPair keyPair = kpg.generateKeyPair();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
// 使用公钥加密
Cipher cipher = Cipher.getInstance("RSA", "BC");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] cipherText = cipher.doFinal(plainText);
System.out.println("Encrypted student id: " + new BigInteger(cipherText));
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
2. 解密学号
```java
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.interfaces.RSAPrivateKey;
import javax.crypto.Cipher;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class RSADecrypt {
public static void main(String[] args) {
try {
BigInteger encryptedStudentId = new BigInteger("1234567890"); // 已加密的学号
// 初始化解密环境
Security.addProvider(new BouncyCastleProvider());
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "BC");
kpg.initialize(4096, new SecureRandom());
// 生成RSA密钥对
KeyPair keyPair = kpg.generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
// 使用私钥解密
Cipher cipher = Cipher.getInstance("RSA", "BC");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] plainText = cipher.doFinal(encryptedStudentId.toByteArray());
System.out.println("Decrypted student id: " + new String(plainText));
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
以上就是基于RSA算法加解密学号的JAVA代码实现,希望能对你有所帮助。
阅读全文
相关推荐










