java实现rsa算法对文件加密解密,且完整提现生成公钥和私钥的过程,给出完整代码
时间: 2023-11-14 08:06:05 浏览: 148
rsa.rar_RSA加密解密和
以下是Java实现RSA算法对文件加密解密的完整代码:
```java
import java.io.*;
import java.security.*;
import javax.crypto.*;
public class RSAFileEncryption {
private static final int RSA_KEY_SIZE = 2048;
public static void main(String[] args) throws Exception {
// Generate public and private keys
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(RSA_KEY_SIZE);
KeyPair keyPair = keyGen.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
System.out.println("Public key:\n" + publicKey);
System.out.println("Private key:\n" + privateKey);
// Write public and private keys to files
ObjectOutputStream publicKeyOut = new ObjectOutputStream(new FileOutputStream("public.key"));
publicKeyOut.writeObject(publicKey);
publicKeyOut.close();
ObjectOutputStream privateKeyOut = new ObjectOutputStream(new FileOutputStream("private.key"));
privateKeyOut.writeObject(privateKey);
privateKeyOut.close();
// Encrypt file using public key
File inputFile = new File("input.txt");
File encryptedFile = new File("encrypted.txt");
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
FileInputStream inputStream = new FileInputStream(inputFile);
FileOutputStream outputStream = new FileOutputStream(encryptedFile);
byte[] inputBytes = new byte[(int) inputFile.length()];
inputStream.read(inputBytes);
byte[] encryptedBytes = cipher.doFinal(inputBytes);
outputStream.write(encryptedBytes);
inputStream.close();
outputStream.close();
// Decrypt file using private key
File decryptedFile = new File("decrypted.txt");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
inputStream = new FileInputStream(encryptedFile);
outputStream = new FileOutputStream(decryptedFile);
byte[] encryptedBytes2 = new byte[(int) encryptedFile.length()];
inputStream.read(encryptedBytes2);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes2);
outputStream.write(decryptedBytes);
inputStream.close();
outputStream.close();
}
}
```
在上面的代码中,我们使用`KeyPairGenerator`类生成公钥和私钥,然后将它们写入文件。我们使用`Cipher`类加密和解密文件。注意,我们使用RSA算法只是对文件进行加密和解密,而不是对文件内容进行数字签名。如果要进行数字签名,需要使用`Signature`类而不是`Cipher`类。
阅读全文