Arduino 和 Android 实现中的 AES 密钥不同

AES keys different in Arduino and Android implementation

我正在尝试使用 AES 算法从 Android 向 Arduino 发送密码。 我在两个加密实现中都面临生成密钥差异的问题。 我确定有一些配置同步。我搜索互联网发现了一些字符串并尝试了所有。但是我的keys/cipher还是不匹配。

欢迎任何意见。

Arduino代码:

void setup()
{
Serial.begin(57600);

}

void loop()
{
  int i = 0;
uint8_t key[] = {0,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6};
char data[] = "sanmacs88       "; //16 chars == 16 bytes
aes128_enc_single(key, data);
Serial.println("encrypted:");
for(i=0;i<16;i++)
Serial.println((int)data[i]);
aes128_dec_single(key, data);
Serial.println("decrypted:");
Serial.println(data);
delay(10000);
  }

输出: 75 45 -7 78 89 123 1个 96 -10 36 110 -105 -119 -11 -7 -8 解密: sanmacs88

Java代码:

public class AES {
  static String IV = "AAAAAAAAAAAAAAAA";
  static String plaintext = "sanmacs88       "; /*Note null padding*/
  static String encryptionKey = "0123456789123456";
  public static void main(String [] args) {
    try {

      System.out.println("==Java==");
      System.out.println("plain:   " + plaintext);

      byte[] cipher = encrypt(plaintext, encryptionKey);

      System.out.print("cipher:  ");
      for (int i=0; i<cipher.length; i++)
        System.out.print(new Integer(cipher[i])+" ");
      System.out.println("");

      String decrypted = decrypt(cipher, encryptionKey);

      System.out.println("decrypt: " + decrypted);

    } catch (Exception e) {
      e.printStackTrace();
    } 
  }

  public static byte[] encrypt(String plainText, String encryptionKey) throws Exception {
    Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding", "SunJCE");
    SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), "AES");
    cipher.init(Cipher.ENCRYPT_MODE, key);
    return cipher.doFinal(plainText.getBytes("UTF-8"));
  }

  public static String decrypt(byte[] cipherText, String encryptionKey) throws Exception{
    Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding", "SunJCE");
    SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), "AES");
    cipher.init(Cipher.DECRYPT_MODE, key);
    return new String(cipher.doFinal(cipherText),"UTF-8");
  }
}      

输出:

plain:   sanmacs88       
cipher:  38 60 69 -111 -44 115 -84 -118 72 -124 86 69 -61 87 -20 63 
decrypt: sanmacs88     

Java键由字符串指定,Arduino键由整数数组指定。

Java键:static String encryptionKey = "0123456789123456";
十六进制:30313233 34353637 38393132 33343536

Arduino 键:uint8_t key[] = {0,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6};
十六进制:00010203 04050607 08090102 03040506 <— 不匹配 Java 键

将 Arduino 键更改为:uint8_t key[] = {"0123456789123456"];
或者:uint8_t key[] = {'0','1','2','3','4','5','6','7','8','9','1','2','3','4','5','6'};