RSA加密的JAVA代码
时间: 2023-10-16 19:10:29 浏览: 37
可以直接调用Java的RSA加密API实现加密/解密功能。需要注意的是,RSA加密需要使用到公钥/私钥对,因此需要生成公钥/私钥对并保存到文件中。以下是一个简单的RSA加密demo代码,仅供参考:
```
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.io.*;
public class RSAEncryption {
private static PublicKey publicKey;
private static PrivateKey privateKey;
private static byte[] publicKeyBytes;
private static byte[] privateKeyBytes;
public static void main(String[] args) {
String message = "";
String cipher = "";
String decrypted = "";
try {
// generate public and private keys
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024);
KeyPair kp = kpg.genKeyPair();
publicKey = kp.getPublic();
privateKey = kp.getPrivate();
// save public and private key to file
publicKeyBytes = publicKey.getEncoded();
privateKeyBytes = privateKey.getEncoded();
FileOutputStream fos = new FileOutputStream("publickey.dat");
fos.write(publicKeyBytes);
fos.close();
fos = new FileOutputStream("privatekey.dat");
fos.write(privateKeyBytes);
fos.close();
// encryption
message = "Hello, world!";
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedMessage = cipher.doFinal(message.getBytes());
cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedMessage = cipher.doFinal(encryptedMessage);
decrypted = new String(decryptedMessage);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Message: " + message);
System.out.println("Encrypted: " + new String(encryptedMessage));
System.out.println("Decrypted: " + decrypted);
}
}
```