java怎么實(shí)現(xiàn)rsa加密解密文件

小億
214
2023-10-26 02:56:24
欄目: 編程語言

要在Java中實(shí)現(xiàn)RSA加密和解密文件,可以使用Java Cryptography Architecture(JCA)提供的RSA算法。以下是一個(gè)簡(jiǎn)單的示例代碼,用于加密和解密文件。

  1. 導(dǎo)入必要的類和包:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import javax.crypto.Cipher;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
  1. 添加Bouncy Castle作為JCA的提供者:
Security.addProvider(new BouncyCastleProvider());
  1. 生成RSA密鑰對(duì):
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", "BC");
keyGen.initialize(2048);
KeyPair keyPair = keyGen.generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();
  1. 加密文件:
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
FileInputStream inputFile = new FileInputStream("input.txt");
FileOutputStream outputFile = new FileOutputStream("encrypted.txt");
byte[] inputBytes = new byte[245];
int bytesRead;
while ((bytesRead = inputFile.read(inputBytes)) != -1) {
    byte[] outputBytes = cipher.doFinal(inputBytes, 0, bytesRead);
    outputFile.write(outputBytes);
}
  1. 解密文件:
cipher.init(Cipher.DECRYPT_MODE, privateKey);
inputFile = new FileInputStream("encrypted.txt");
outputFile = new FileOutputStream("decrypted.txt");
byte[] encryptedBytes = new byte[256];
while ((bytesRead = inputFile.read(encryptedBytes)) != -1) {
    byte[] decryptedBytes = cipher.doFinal(encryptedBytes, 0, bytesRead);
    outputFile.write(decryptedBytes);
}

請(qǐng)注意,上述代碼使用Bouncy Castle作為JCA的提供者,并假設(shè)輸入文件名為"input.txt",加密后的文件名為"encrypted.txt",解密后的文件名為"decrypted.txt"。此外,還假設(shè)輸入文件不超過245個(gè)字節(jié),加密后的文件長度為256個(gè)字節(jié)。您可以根據(jù)實(shí)際需要進(jìn)行修改。

0