How to do encryption using AES in Openssl

后端 未结 4 1590
野趣味
野趣味 2020-12-02 07:28

I am trying to write a sample program to do AES encryption using Openssl. I tried going through Openssl documentation( it\'s a pain), could not figure out much. I went throu

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-02 07:52

    I don't know what's wrong with yours but one thing for sure is you need to call AES_set_decrypt_key() before decrypting the message. Also don't try to print out as %s because the encrypted message isn't composed by ascii characters anymore.. For example:

    static const unsigned char key[] = {
        0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
        0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff,
        0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
        0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f
    };
    
    int main()
    {
        unsigned char text[]="hello world!";
        unsigned char enc_out[80];
        unsigned char dec_out[80];
    
        AES_KEY enc_key, dec_key;
    
        AES_set_encrypt_key(key, 128, &enc_key);
        AES_encrypt(text, enc_out, &enc_key);      
    
        AES_set_decrypt_key(key,128,&dec_key);
        AES_decrypt(enc_out, dec_out, &dec_key);
    
        int i;
    
        printf("original:\t");
        for(i=0;*(text+i)!=0x00;i++)
            printf("%X ",*(text+i));
        printf("\nencrypted:\t");
        for(i=0;*(enc_out+i)!=0x00;i++)
            printf("%X ",*(enc_out+i));
        printf("\ndecrypted:\t");
        for(i=0;*(dec_out+i)!=0x00;i++)
            printf("%X ",*(dec_out+i));
        printf("\n");
    
        return 0;
    } 
    

    U1: your key is 192 bit isn't it...

提交回复
热议问题