c ++:将字符串转换为十六进制字节数组?

时间:2015-02-22 22:20:28

标签: c++ encryption aes mbed

我正在使用mbed微控制器并使用c ++编程。我有一个包含JSON数据的字符串。如何将JSON字符串转换为十六进制字节数组,然后使用AES128加密数据,并在需要时填充JSON字符串?另外,如何将十六进制字节数组转换为ascii?

我正在使用这个c ++示例:

#include "mbed.h"
#include "Crypto.h"

Serial pc(USBTX, USBRX);
unsigned char myKEY[16] = {0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F,};
unsigned char myIV[16] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, } ;
unsigned char msg[0x60] =
{
    0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 
    0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 
    0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 
    0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 
} ;
int main()
{
    pc.baud (115200);
    pc.printf("\r\nCleartext");
    for(char i=0; i<0x60; i++) 
    {
        if(i%16==0) pc.printf("\r\n");
        pc.printf("%.2X",msg[i]);
    }

    // init crypto
    //AES myAES(AES_128, myKEY); // will default to ECB_MODE
    //AES myAES(AES_128, myKEY, myIV); // will default to CBC_MODE
    AES myAES(AES_128, myKEY, myIV, PCBC_MODE); // specify all params, look at BlockCipher.h for modes
    pc.printf("\r\n\r\nFirst run\r\n");
    myAES.encrypt(msg,msg,0x60); // same in and out buffer can be used
    pc.printf("\r\nEncrypted");
    for(char i=0; i<0x60; i++) 
    {
        if(i%16==0) pc.printf("\r\n");
        pc.printf("%.2X",msg[i]);
    }
    pc.printf("\r\nDecrypted again");
    myAES.decrypt(msg,msg,0x60);
    for(char i=0; i<0x60; i++) 
    {
        if(i%16==0) pc.printf("\r\n");
        pc.printf("%.2X",msg[i]);
    }
    // change key and IV without reinit all
    unsigned char newKey[16];
    unsigned char newIV[16];
    memset(newKey, 0x22, 16);
    memset(newIV, 0x33, 16);
    myAES.keyExpansion(newKey);
    myAES.setIV(newIV);
    pc.printf("\r\n\r\nKey and IV changed\r\n");
    unsigned char plaintext[0x60];
    unsigned char ciphertext[0x60];
    myAES.encrypt(ciphertext,msg,0x60); // different buffers if you have space
    pc.printf("\r\nEncrypted");
    for(char i=0; i<0x60; i++) 
    {
        if(i%16==0) pc.printf("\r\n");
        pc.printf("%.2X",ciphertext[i]);
    }
    pc.printf("\r\nDecrypted again");
    myAES.decrypt(plaintext,ciphertext,0x60); // different buffers if you have space
    for(char i=0; i<0x60; i++) 
    {
        if(i%16==0) pc.printf("\r\n");
        pc.printf("%.2X",plaintext[i]);
    }

}

0 个答案:

没有答案