2016-03-27 4 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バイト)。 @ArtjomB。 –

+0

このヒントをありがとう!私にはOAEPのコード例がありますか? – Christian

答えて

2

まず、cipherEncoderを使用してデータをデコードしています。あなたはおそらくcipherDecoderを使うつもりです。第2に、パディングなしで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

関連する問題