2016-03-27 80 views
0

我想創建RSA密鑰對並將其用於編碼/解碼數據。我的代碼很短,但我找不到任何錯誤。直接編碼/解碼不會產生原始數據

任何人都可以幫我找到我的問題嗎?

感謝您的每一個提示!

// Generate key pair. 
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); 
kpg.initialize(1024, new SecureRandom()); 
KeyPair keyPair = kpg.genKeyPair(); 
PublicKey publicKey = keyPair.getPublic(); 
PrivateKey privateKey = keyPair.getPrivate(); 

// Data to encode/decode. 
byte[] original = "The quick brown fox jumps over the lazy dog.".getBytes("UTF8"); 

// Encode data with public key. 
Cipher cipherEncoder = Cipher.getInstance("RSA/ECB/NoPadding"); 
cipherEncoder.init(Cipher.ENCRYPT_MODE, publicKey); 
byte[] encodedData = cipherEncoder.doFinal(original); 

// Decode data with private key. 
Cipher cipherDecoder = Cipher.getInstance("RSA/ECB/NoPadding"); 
cipherDecoder.init(Cipher.DECRYPT_MODE, privateKey); 
byte[] decodedData = cipherEncoder.doFinal(encodedData); 

// Output. 
System.out.println(new String("Original data: " + new String(original, "UTF8"))); 
System.out.println(new String("Encoded/decoded: " + new String(decodedData, "UTF8"))); 

最後的輸出似乎很古怪。

+1

顯示輸出... – fge

+1

教科書RSA(沒有填充)真的不安全。也不應該使用PKCS#1 v1.5填充(11字節開銷)。如今,建議使用OAEP(SHA1的開銷爲42字節)。 –

+0

@ ArtjomB。感謝這個提示!你有我的OAEP代碼示例嗎? – Christian

回答

2

首先,您正在使用cipherEncoder來解碼您的數據。您可能打算使用cipherDecoder。其次,使用RSA時沒有填充會出現問題(即,您的數據在開始時將有一個0字節的負載)。我會建議你至少使用PKCS1填充。以下是這些更改後的代碼。

// Generate key pair. 
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); 
kpg.initialize(1024, new SecureRandom()); 
KeyPair keyPair = kpg.genKeyPair(); 
PublicKey publicKey = keyPair.getPublic(); 
PrivateKey privateKey = keyPair.getPrivate(); 

// Data to encode/decode. 
byte[] original = "The quick brown fox jumps over the lazy dog.".getBytes("UTF8"); 

// Encode data with public key. 
Cipher cipherEncoder = Cipher.getInstance("RSA/ECB/PKCS1Padding"); 
cipherEncoder.init(Cipher.ENCRYPT_MODE, publicKey); 
byte[] encodedData = cipherEncoder.doFinal(original); 

// Decode data with private key. 
Cipher cipherDecoder = Cipher.getInstance("RSA/ECB/PKCS1Padding"); 
cipherDecoder.init(Cipher.DECRYPT_MODE, privateKey); 
byte[] decodedData = cipherDecoder.doFinal(encodedData); 

// Output. 
System.out.println(new String("Original data: " + new String(original, "UTF8"))); 
System.out.println(new String("Encoded/decoded: " + new String(decodedData, "UTF8"))); 
+0

非常感謝您的回答,並找到我的錯誤。做得好! – Christian