我使用字符串實現了客戶端和服務器之間的通信。我得到的問題是將所描述的字節數組轉換爲字符串,因爲我無法將其轉換回服務器端的原始內容。數據類型轉換時的Java加密問題
KeyPairGenerator keyGen;
keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(1024);
KeyPair key = keyGen.generateKeyPair();
String publicKeyPath = new String("publicKeys.txt");
publickey = key.getPublic()
byte[] pubEncoded = key.getPublic().getEncoded();
FileOutputStream fout = new FileOutputStream(publicKeyPath);
fout.write(pubEncoded);
fout.flush();
fout.close();
String privateKeyPath = new String("privateKeys.txt");
byte[] privEncoded = key.getPrivate().getEncoded();
fout = new FileOutputStream(privateKeyPath);
fout.write(privEncoded);
fout.flush();
fout.close();
cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
而且在客戶端的每個方法:
cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publickey);
byte[] cipherText = cipher.doFinal(str.getBytes());
port.callX(chiperText.toString());
在服務器端:
cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] newPlainText = cipher.doFinal(arg.getBytes());
這給出了填充問題
「的數據必須以零開始」只有一個KeyPair生成,用於調試,我試圖對同一個函數進行加密和解碼,並且問題依賴於從byte []轉換爲String。
我真的不想改變參數傳遞給其他類型,因爲操作是自動生成的,所有代碼都是字符串。我已經嘗試了不同的「UTF-8」和「UTF-16Le」,但沒有任何作品:S
任何想法?
你爲什麼在整個地方調用String(String)構造函數,出於興趣? –
沒有特別的理由......你可以把它改成String path =「XX」這個問題與文件路徑無關。它存儲的密鑰很好 – d0pe
當然 - 這只是奇怪的代碼,就是這樣。 –