2010-12-10 24 views
9

私はAndroidでAESを使用して文字列を暗号化しようとしています。対称キーはDiffie-Hellmanアルゴリズムで以前に決定されており、キーの長さは128ビットです(下を参照)。AES暗号化:InvalidKeyException:キーの長さが128/192/256ではない

KeyAgreement keyAgree = KeyAgreement.getInstance("DH", "BC"); 
keyAgree.init(this.smartphonePrivKey); 
keyAgree.doPhase(serverPubKey, true); 
SecretKey key = keyAgree.generateSecret("AES"); 
System.out.println("Key Length: " + key.getEncoded().length); 
System.out.println("Key Algorithm: "+ key.getAlgorithm()); 
System.out.println("Key Format: "+ key.getFormat()); 

byte[] encrypted = null; 
    Cipher cipher; 
    try { 
    cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); 
    System.out.println("Allowed Key Length: " 
    + cipher.getMaxAllowedKeyLength("AES")); 
    cipher.init(Cipher.ENCRYPT_MODE, key); 
    encrypted = cipher.doFinal("YEAH".getBytes("UTF8")); 
    } catch (NoSuchAlgorithmException e) { 
    e.printStackTrace(); 
    } catch (NoSuchPaddingException e) { 
    e.printStackTrace(); 
    } catch (InvalidKeyException e) { 
    e.printStackTrace(); 
    } catch (IllegalBlockSizeException e) { 
    e.printStackTrace(); 
    } catch (BadPaddingException e) { 
    e.printStackTrace(); 
    } catch (UnsupportedEncodingException e) { 
    e.printStackTrace(); 
    } 

上記のコードは次の出力につながる:その後

_12-10 20:24:53.119: INFO/System.out(757): Key Length: 128_ 
_12-10 20:24:53.119: INFO/System.out(757): Key Algorithm: AES_ 
_12-10 20:24:53.119: INFO/System.out(757): Key Format: RAW_ 
_12-10 20:24:53.470: INFO/System.out(757): Allowed Key Length: 2147483647_ 

あなたが見ることができるように、私はInvalidKeyException: Key length not 128/192/256 bits.を得る。しかし
はそれにもかかわらず、私はInvalidKeyException: "Key length not 128/192/256 bits.

コードを取得しますSecretKeyの長さは128ビットです。

アイデア?

答えて

19

作成したキーは128 バイトで、128 ビットのではありません。 "キーの長さ"は16にする必要があります。

+0

1は、それを私にビート。 @Peter:ビット数を表すLengthプロパティが見つかる唯一の場所は特殊なビットコレクションです。 99.9%の時間は文字数またはバイト数になります。 –

+0

うーん、あなたは明らかに正しい。したがって、KeyAgreement.generateSecret( "AES")を使用すると、128バイトの長さのキーが返されます。明らかに、それはあまりにも多すぎます...私は256ビットと言うと、どのようにして鍵を得ることができますか?ありがとう – Peter

+0

ところで、AndroidはセキュリティプロバイダとしてBouncyCastleを使用しています... – Peter

1

この例外は基本的に暗号化に渡された鍵の長さのために発生します.AES暗号化を使用している場合、文字数は128/192/256ビット。 たとえば、16文字、24文字または32文字のキーを使用できます。

String encrypted_data=AES.encrypt("HELLO","ASDFGHJKLASDFGHJ"); 

・ホープ、このヘルプ...

+0

すでに受け入れられている回答があります。 –

関連する問題