AES加密:使用Arduino进行加密,使用Java进行解密

3
我希望使用Arduino加密文本,并使用Java进行解密。我尝试了这个链接中的代码,但没有成功。
我在Arduino上使用AES库进行加密,在Java侧使用Java密码扩展(JCE)框架。
以下是Arduino代码:
#include <AESLib.h>  //replace the ( with < to compile (forum posting issue)
#include <Base64.h>

void setup() {
  Serial.begin(9600);
  uint8_t key[] = {50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50};
  //expressed in 16 unsigned in characters, be careful not to typecast this as a char in a decrypter
  //16- 50's (uint8) is the way to express 16 2's in ASCII, the encryption matches to what will show up on <a href="http://aesencryption.net/" target="_blank" rel="nofollow">http://aesencryption.net/</a>
  char data[] = "0123456789012345";
  //The message to encrypt, 16 chars == 16 bytes, no padding needed as frame is 16 bytes
  char encryptedData[100];
  int *size;
  Serial.print("Message:");
  Serial.println(data);
  aes128_enc_single(key, data);
  Serial.print("encrypted:");
  Serial.println(data);
  int inputLen = sizeof(data);
  int encodedLen = base64_enc_len(inputLen);
  char encoded[encodedLen];
  base64_encode(encoded, data, inputLen);
  Serial.print("encrypted(base64):"); //used
  Serial.println(encoded);
  Serial.println("***********Decrypter************");
  int input2Len = sizeof(encoded);
  int decodedLen = base64_dec_len(encoded, input2Len);
  char decoded[decodedLen];
  base64_decode(decoded, encoded, input2Len);
  Serial.print("encrypted (returned from Base64):");
  Serial.println(decoded);
  Serial.print("decrypted:");
  Serial.println(decoded);
}

void loop() {
}

这是Java代码:

package main;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;

public class ForTest {
    public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
        String message= "0123456789012345";//Message to encode  
        String key = "2222222222222222"// 128 bit key  -this key is processed as ASCII values  
        System.out.println("Processing 3.0 AES-128 ECB Encryption/Decryption Example");
        System.out.println("++++++++++++++++++++++++++++++++");
        System.out.println("Original Message: " + message);
        System.out.println("Key: " + key);
        System.out.println("key in bytes: "+key.getBytes("UTF-8"));
        System.out.println("==========================");           
        //Encrypter
        SecretKeySpec skeySpec_encode = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
        Cipher cipher_encode  = Cipher.getInstance("AES/ECB/NoPadding");
        //          Cipher cipher_encode = Cipher.getInstance("AES/ECB/PKCS5PADDING"); //AES-CBC with IV encoding, ECB is used without the IV, example shown on <a href="http://aesencryption.net/" target="_blank" rel="nofollow">http://aesencryption.net/</a> 
        cipher_encode.init(Cipher.ENCRYPT_MODE, skeySpec_encode);
        byte[] encrypted = cipher_encode.doFinal(message.getBytes());
        System.out.println("Encrypted String (base 64): "
                + DatatypeConverter.printBase64Binary(encrypted));
        //encode without padding: Base64.getEncoder().withoutPadding().encodeToString(encrypted));
        //encode with padding:  Base64.getEncoder().encodeToString(encrypted));
        String base64_encrypted = DatatypeConverter.printBase64Binary(encrypted);
        //Decrypter
        SecretKeySpec skeySpec_decode = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
        Cipher cipher_decode  = Cipher.getInstance("AES/ECB/NoPadding");
        //          Cipher cipher_decode = Cipher.getInstance("AES/ECB/PKCS5PADDING");
        cipher_decode.init(Cipher.DECRYPT_MODE, skeySpec_decode);
        System.out.println("length: "+"Ouril+UTDF8htLzE".length());
        byte[] decrypted_original = cipher_decode.doFinal(DatatypeConverter.parseBase64Binary("Ouril+UTDF8htLzEhiRj7wA="));
        String decrypt_originalString = new String(decrypted_original);
        System.out.println("Decrypted String: " + decrypt_originalString);
    }
}

在Java中,当我尝试通过Arduino解密编码的字符串时,我得到了以下结果:
Processing 3.0 AES-128 ECB Encryption/Decryption Example
++++++++++++++++++++++++++++++++
Original Message: 0123456789012345
Key: 2222222222222222
key in bytes: [B@2a139a55
==========================
Encrypted String (base 64): Ouril+UTDF8htLzEhiRj7w==
length: 16
Exception in thread "main" javax.crypto.IllegalBlockSizeException: Input length not multiple of 16 bytes
    at com.sun.crypto.provider.CipherCore.finalNoPadding(CipherCore.java:1016)
    at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:960)
    at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:824)
    at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:436)
    at javax.crypto.Cipher.doFinal(Cipher.java:2165)
    at main.ForTest.main(ForTest.java:46)

有什么想法吗?谢谢!

4
你试图对其进行base64解码和解密的字符串是Ouril+UTDF8htLzEhiRj7wA=, 经过base64解码后长度为17字节,末尾有一个0字节。之前打印出来的字符串是Ouril+UTDF8htLzEhiRj7w==,除了末尾的那个字节以外完全相同(经过base64解码),并且它的长度是正确的(16个字节)。 - matt
1
Arduino输出引入了一个额外的字节。我对Arduino语言本身不熟悉,但是从快速查看来看,它是C/C++的子集。C以“空终止”其字符串而闻名(即为了表示字符串的结尾,它添加一个包含值0x00的字节,该字符串具有任意长度)。这很可能就是在这里发生的事情。 - Andy
1
在Java代码中,您需要将输入密码文本修剪到0x00字节之前的字节。此外,如果输入明文和密码文本不是完全16字节的倍数(AES的块大小),则您选择的AES/ECB/NoPadding将会出现严重问题,并且ECB是最糟糕的密码块模式(对于大多数目的相当于_未加密_)。请查看密码块运算模式的维基百科条目,并选择更好的选项(建议使用GCM进行AEAD属性)。 - Andy
1
你也可以在源代码中解决这个问题,只需在Arduino中对密文内容进行Base64编码,直到空字节为止,但我不知道是否有简单的方法来实现这一点。你可以尝试在对char[]进行编码之前将最后一个字节删除。 - Andy
@sabrina2020你好,你最后解决这个问题了吗?我也遇到了同样的问题,并且一直在尝试删除Arduino Strings、char数组等末尾的空终止符号。显然,编译器总是会插入它们。让Arduino/C++与Java进行AES base 64编码的方式保持同步,让我有些头疼:) 我可以在Arduino上很好地实现AES base 64编码进行加密和解密,但是当我将其发送到我的Java服务器时,它总是抛出一个填充错误。你有什么想法吗? - Mike
显示剩余2条评论
1个回答

2

经过一周的努力,我终于让它工作了 - 与其他系统集成的Arduino文档真是糟糕:)

工作中的Arduino代码:

#include "mbedtls/aes.h"
#include <Arduino.h>
#include <HTTPClient.h>
#include <base64.h>

void makeUpdateAPICall()
{
  if (WiFi.status() == WL_CONNECTED)
  {
    HTTPClient http;

    // Your Domain name with URL path or IP address with path
    http.begin(serverName); 

    // Specify content-type header
    http.addHeader("Content-Type", "text/plain");
    http.addHeader("Authorization", "Bearer XXXXXXXX [whatever your web token is]");
    http.addHeader("X-Content-Type-Options", "nosniff");
    http.addHeader("X-XSS-Protection", "1; mode=block");

    //AES Encrypt
    esp_aes_context aesOutgoing;
    unsigned char key[32] = "1234567812345678123456781234567" ;
    key[31] = '8';   // we replace the 32th (index 31) which contains '/0' with the '8' char.

    char *input = "Tech tutorials x";
    unsigned char encryptOutput[16];

    mbedtls_aes_init(&aesOutgoing);
    mbedtls_aes_setkey_enc(&aesOutgoing, key, 256);
    int encryptAttempt = mbedtls_aes_crypt_ecb(&aesOutgoing, MBEDTLS_AES_ENCRYPT, (const unsigned char *)input, encryptOutput);
    USE_SERIAL.println();
    USE_SERIAL.println("MBEDTLS_AES_EBC encryption result:\t ");
    USE_SERIAL.print(encryptAttempt); //0 means that the encrypt/decrypt function was successful
    USE_SERIAL.println();
    mbedtls_aes_free(&aesOutgoing);

    int encryptSize = sizeof(encryptOutput) / sizeof(const unsigned char);
    USE_SERIAL.println("Size of AES encrypted output: ");
    USE_SERIAL.println(encryptSize);

    //Base 64 Encrypt
    int inputStringLength = sizeof(encryptOutput);
    int encodedLength = Base64.decodedLength((char *)encryptOutput, inputStringLength);
    char encodedCharArray[encodedLength];
    Base64.encode(encodedCharArray, (char *)encryptOutput, inputStringLength);
    //Send to server
    USE_SERIAL.print("Sending to server.");
    int httpResponseCode = http.POST(encodedCharArray);

    String payload = "{}";

    if (httpResponseCode > 0)
    {
      //Retrieve server response
      payload = http.getString();
    }
    // Free resources
    http.end();
  }
  WiFi.disconnect();
}

Java代码示例:

public static String decrypt(String strToDecrypt, String key) {

    byte[] encryptionKeyBytes = key.getBytes();  
    Cipher cipher;
    try {
        cipher = Cipher.getInstance("AES/ECB/NoPadding");
        SecretKey secretKey = new SecretKeySpec(encryptionKeyBytes, "AES");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);         
        return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt.getBytes("UTF-8"))));
    } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    } catch (BadPaddingException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

现在正在处理返回过程。

您可以使用以下代码调用Java端:

final String decryptedText = AES.decrypt(encryptedStr, "12345678123456781234567812345678"); System.out.println("解密AES ECB字符串:"); System.out.println(decryptedText);

希望为任何陷入同样困境的可怜家伙提供帮助:)

希望这有所帮助!


这个固定大小的加密输出并没有太大用处,而且将密钥作为字符串的所有花哨操作都是不必要的:如果您像OP中那样保留它,那么尾随的空值问题就不会出现。 - user207421
1
@user207421 你说得很对。然而,我的示例的目的只是为了提供一种在Arduino和Java之间集成AES的可行方法。实际上没有文档(至少我找不到)。我的生产代码使用填充、AES CBC,并从服务器上的安全位置提取密钥。从安全位置提取密钥和其他东西更像是日常工作,但关键是让来自其他系统/语言的解密/加密部分能够正常工作。希望这能帮助某些人克服这个障碍。 - Mike

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接