Java " />

扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

java鎬庝箞瀹炵幇rsa鍔犲瘑瑙e瘑鏂囦欢

扬州沐宇科技
2023-10-26 02:56:24
Java

瑕佸湪Java涓疄鐜癛SA鍔犲瘑鍜岃В瀵嗘枃浠讹紝鍙互浣跨敤Java Cryptography Architecture锛圝CA锛夋彁渚涚殑RSA绠楁硶銆備互涓嬫槸涓€涓畝鍗曠殑绀轰緥浠g爜锛岀敤浜庡姞瀵嗗拰瑙e瘑鏂囦欢銆?/p>

  1. 瀵煎叆蹇呰鐨勭被鍜屽寘锛?/li>
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瀵嗛挜瀵癸細
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", "BC");
keyGen.initialize(2048);
KeyPair keyPair = keyGen.generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();
  1. 鍔犲瘑鏂囦欢锛?/li>
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. 瑙e瘑鏂囦欢锛?/li>
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);
}

璇锋敞鎰忥紝涓婅堪浠g爜浣跨敤Bouncy Castle浣滀负JCA鐨勬彁渚涜€咃紝骞跺亣璁捐緭鍏ユ枃浠跺悕涓?quot;input.txt"锛屽姞瀵嗗悗鐨勬枃浠跺悕涓?quot;encrypted.txt"锛岃В瀵嗗悗鐨勬枃浠跺悕涓?quot;decrypted.txt"銆傛澶栵紝杩樺亣璁捐緭鍏ユ枃浠朵笉瓒呰繃245涓瓧鑺傦紝鍔犲瘑鍚庣殑鏂囦欢闀垮害涓?56涓瓧鑺傘€傛偍鍙互鏍规嵁瀹為檯闇€瑕佽繘琛屼慨鏀广€?/p>

扫码添加客服微信