18

AndroidでAESを使用して文字列を暗号化しようとしています。対称鍵は、Diffie-Hellmanアルゴリズムを使用して事前に決定されており、問題ないようです(鍵の長さは128ビットです。以下を参照してください)。
それにもかかわらず、私は InvalidKeyException: "Key length not 128/192/256 bits.

コード:

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.しますが、ご覧のとおり、SecretKeyの長さは128ビットです。

何か案は?

4

2 に答える 2

30

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

于 2010-12-10T21:02:11.683 に答える
9

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

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

この助けを願っています...

于 2017-01-31T05:47:04.250 に答える