2011-11-11 5 views
2

これは私の最初の質問ですので、何かを得るための十分な情報を提供したいと思います私は(IMO)非常に基本的な公開鍵の暗号化/解読の問題を抱えています。公開鍵をクライアントに渡して暗号化された情報(RSA)を復号化する際の問題(javax.crypto.BadPaddingException)

私は例を試してみましたが、何が間違っているかを調べるためにAPIを読みましたが、これまでのところ、このような理由で解読に失敗した理由を解明できませんでした基本的なテスト...

私はクライアントとサーバーの間で転送するすべてのもののヘクスを印刷しており、それらは同じようです。私はさまざまなパディングと暗号を使用しようとしましたが、どれもうまくいかないようです。二つのプログラムから

コード(私は非本質的なプリントアウトを編集した):

Serverコード:

RSAKeyPairGenerator kpg = new RSAKeyPairGenerator(); 
kpg.initialize(1024); 
KeyPair kp = kpg.generateKeyPair(); 
PublicKey pk = kp.getPublic(); 
PrivateKey pri = kp.getPrivate(); 
InputStream in = csocket.getInputStream(); 
OutputStream out = csocket.getOutputStream(); 
DataInputStream dis = new DataInputStream(in); 
DataOutputStream dos = new DataOutputStream(out); 

// write getEncoded().length 
dos.writeInt(pk.getEncoded().length); 

// write key 
byte[] public_key = pk.getEncoded(); 
for (int x=0;x<public_key.length;x++) { 
    dos.writeByte(public_key[x]); 
} 
dos.flush(); 

// read enc length 
int len=dis.readInt(); 
byte[] data = new byte[len]; 

// read enc stuff 
System.out.println("Read data:"); 
for (int x=0;x<len;x++) { 
    data[x]=dis.readByte(); 
} 
// decrypt 
byte [] decrypted = null; 
try { cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); 
    cipher.init(Cipher.DECRYPT_MODE, pri); 
    decrypted = cipher.doFinal(new String(data).getBytes()); 
} catch (Exception e) { e.printStackTrace(); } 

クライアント:

InputStream in = socket.getInputStream(); 
OutputStream out = socket.getOutputStream(); 
DataInputStream dis = new DataInputStream(in); 
DataOutputStream dos = new DataOutputStream(out); 

// Read key length 
int len = dis.readInt(); 

// Read key 
byte[] public_key = new byte[len]; 
byte[] tmp = new byte[1]; 
for (int x = 0; x<len; x++) { 
    public_key[x] = dis.readByte(); 
} 

try { 
    keySpec = new X509EncodedKeySpec(public_key); 
    keyFactory = keyFactory.getInstance("RSA"); 
    publicKey = keyFactory.generatePublic(keySpec); 
} catch (Exception e) { e.printStackTrace(); } 

try { 
    cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "IBMJCE"); 
    cipher.init(Cipher.ENCRYPT_MODE, publicKey); 
    // crypt string 
    data = cipher.doFinal(new String("Encrypt this").getBytes()); 
} catch (Exception e) { e.printStackTrace(); } 

// write data.length 
dos.writeInt(data.length); 

// write encrypted data 
for (int x=0; x<data.length;x++) { 
     dos.writeByte(data[x]); 
} 
dos.flush(); 
+1

何らかの理由あなたは 'Cipher'オブジェクトをクライアントとサーバの両方でまったく同じ方法で取得しませんか? – Romain

+0

'cipher.doFinal(new String(data).getBytes());'は意味を持たず、おそらく間違っています。単純な 'cipher.doFinal(data);だけではないのですか? –

+0

こんにちは、残念です。ロマン:なぜ私は同じマシン上でこれを実行しているように、暗号が違うのか想像できませんので、環境は同じで、パラメータも同じですか? @Greg:doFinalは、上のコードのように残念ながら残っていましたが、私は問題を解決するためにあらゆる種類のことを試していました。 これをdoFinal(data)に戻すと実際に問題が解決されているかもしれません...私は本当に私が試したことと変更したことをよりよく把握しておくべきだと思っています...解決してくれてありがとう完全な初心者のように:) – Kapu

答えて

0

これに対する答え問題は:自分のコードを読んで、あなたがしたことを把握することを学ぶ...あなたの時間を無駄にして申し訳ありません:/

関連する問題