Encryption software

Hi all,

I'm currently working on encrypting a .bin file , using the crypto api. 

However I'd like to know if it's possible to encrypt , this .bin file, using a third part windows software and then decrypting using the crypto api on my S7G2

chip.

And if  it's possible , Does anyone have any suggestion of what software could do that ??

 

Ps: I already can encrypt a .bin file using the crypto api, but i really would like to know if its possible to encrypt this file using a third part windows software.

 

Regards,

 

Phillipe

  • Hi,

     

    The below Python code will encrypt a file and send via serial to a Synergy host. It uses AES-CBC 256 bit encryption. This code is taken from a Renesas lab. The indentation will need to fixed.

     

    Regards,

     

    Ian.

     

     

    from __future__ import print_function
    from Crypto.Cipher import AES
    from Crypto.Random import get_random_bytes
    from Crypto.Util.Padding import pad
    from Crypto.Util.Padding import unpad
    from Crypto.PublicKey import RSA
    from Crypto.Signature import pkcs1_15
    from Crypto.Hash import SHA256
    import serial
    import time
    import sys
    import getopt

    # Serial data format
    # Number of bytes in encrypted message (incluing padding), IV and number of actual bytes in the plain text message
    # Number of bytes in the decrypted plain text (unpadded) data
    # Initialisation vector (IV) - 16 bytes
    # Encrypted message (multiples of 16 byte chunks)
    # Signature (256 bytes)

    key = b'\x77\x3F\x36\xF8\x7D\x43\xEB\xF8\x86\x99\xCF\x93\x01\xDD\x9B\xD7\x79\xA6\xDF\x53\xBA\xDB\xBE\x0A\x3F\x5C\x90\xE0\x8F\xE1\xE3\xF2'
    #773F36F87D43EBF88699CF9301DD9BD779A6DF53BADBBE0A3F5C90E08FE1E3F2

    def print_instructions():
    print("Usage:")
    print("\tpython file_encrypt_sign_send.py -i <input_file> -v <private_key_file> -b <public_key_file> -c <COM port>")
    print()
    print("\t<input_file> is the file to be encrypted, signed and sent to the Synergy device.")
    print("\t<COM port> is the PC COM port e.g. COM5")
    print()
    print("Use generate_rsa_keys.py program to generate the private and public PEM formatted RSA keys.")

    def format_length(length):
    len_packet = bytearray()
    # 0xAABBCCDD
    # Send AA
    x = (length & 0xFF000000) >> 24
    len_packet.append(int(x))
    # Send BB
    x = (length & 0x00FF0000) >> 16
    len_packet.append(int(x))
    # Send CC
    x = (length & 0x0000FF00) >> 8
    len_packet.append(int(x))
    # Send DD
    x = length & 0x000000FF
    len_packet.append(int(x))
    #
    return len_packet

    def main(argv):
    try:
    opts, args = getopt.getopt(argv, "hi:b:v:c:",["ifile=", "cport="])
    except getopt.GetoptError:
    print_instructions()
    exit()

    for opt, arg in opts:
    if(opt =='-h'):
    print_instructions()
    exit()
    elif opt in ("-i", "--ifile"):
    inputfile = arg
    elif opt in ("-c", "--cport"):
    comport = arg

    # Open COM port
    try:
    ser = serial.Serial(comport)
    print("Comms open.")
    except:
    print("Failed to open COM port. Exiting.")
    exit()

    # Open source file to encrypt
    try:
    f = open(inputfile, "r")
    plaintext = f.read()
    print("Reading file contents.")
    f.close()
    except:
    print("Could not open file: ", inputfile)
    # Close the comms
    ser.close()
    print("Comms closed.")
    exit()


    #################################
    # Encrypt #
    #################################
    # Create a random initialisation vector (16 bytes)
    iv = get_random_bytes(16)

    # Create an AES cipher with the key and initialisation vector
    cipher = AES.new(key, AES.MODE_CBC, iv)

    # Pad and encrypt the plaintext data
    msgb = cipher.encrypt(pad(plaintext.encode('utf-8'), 16))

    # Send encrypted data
    # First send the number of bytes in the IV plus the encrypted data
    # 32-bit number so send 4 bytes
    msg = bytes(msgb)
    msg_len = 16 + len(msg) # 16 IV bytes + length of encrypted message
    packet = format_length(msg_len)
    ser.write(packet)
    print("Sending length of encrypted (padded) message and IV.")
    print("Length header: "+str(msg_len))

    # Send the length of the plaintext message
    msg_len = len(plaintext)
    packet = format_length(msg_len)
    ser.write(packet)
    print("Sending length of plaintext (unpadded) message.")
    print("Plaintext message length: "+str(msg_len))

    # Send the IV plus encrypted data
    ser.write(iv)
    print("Sending IV...")

    print("Sending encrypted message data.")
    print("Message Length: "+str(len(msg)))
    # Send in 16 byte chunks for benefit of USB CDC on Synergy at the other end
    for i inrange (0, len(msg), 16):
    ser.write(msg[i:i+16])
    print(".", end='')
    print("")

    print("")
    print("All data sent.")

    # Close the comms
    ser.close()
    print("Comms closed.")

    if __name__ == "__main__":
    main(sys.argv[1:])
  • In reply to Ian:

    Hi Ian,

    Thank you very much for your reply !


    I'm found the library openssl and i am using it to encrypt a simple text file that has the message "Hello World!"

    The comand that i'm using to encrypt the text file is

    -k encryption key
    -iv initialization vector

    enc -nosalt -aes-128cbc -in file.txt -out file_encrypt.txt -k 11111111111111111111111111111111
    -iv 11111111111111111111111111111111


    Then i tried to decrypt the file "file_encrypt.txt" using my renesas s7g2 host, however i cannot get the original message back ("Hello World!")


    I set the aes128 key vector and Initialization vector as it follows :

    uint32_t aes128key[4] = { 0x11111111,0x11111111,0x11111111,0x11111111 };

    uint32_t aes128iv[4] ={ 0x11111111,0x11111111,0x11111111,0x11111111 };

    And finally i use the decrypt api :

    g_aes128cbc_on_sce.decrypt(&aes_ctrl,aes128key,aes128iv, sizeof(input_buffer), input_buffer,decrypt_buffer);

    I wonder if i'm setting the key and initialization vector correctly on the buffers or maybe because the encryption is made on a pc , i cannot decrypt on the microcontroler.

    One more thing ,the api for the aes 128-cbc encryption and decryption process does not use salt ,right?


    Thank you in advance.

  • In reply to Phillipe:

    Hi,

    Can you try -K instead of -k on the OpenSSL command line? -K means the key is a hex value.

    Regards,

    Ian.
  • In reply to Ian:

    Hi Ian,

    My mistake, i was trying with -k , but even using -K i still couldn't get the original message.


    the command that i typed now is :

    enc -nosalt -aes-128cbc -in file.txt -out file_encrypt.txt -K 11111111111111111111111111111111
    -iv 11111111111111111111111111111111


    My key and iv vector are as it follows below :

    uint32_t aes128key[4] = { 0x11111111,0x11111111,0x11111111,0x11111111 };

    uint32_t aes128iv[4] ={ 0x11111111,0x11111111,0x11111111,0x11111111 };


    g_aes128cbc_on_sce.decrypt(&aes_ctrl,aes128key,aes128iv, sizeof(input_buffer), input_buffer,decrypt_buffer);


    by the way , my input_buffer and decrypt_buffer is a uint8_t[16] .


    Is it possible that i cannot decrypt on my S7G2 host a message encrypted on a PC.

    Does the endianess flag has any influence on this decryption case.

    kind regards,

    Phillipe

  • In reply to Phillipe:

    In my experience the endian should be set to little.

    I will try and put something together to get it working.

    Regards,

    Ian.
  • In reply to Ian:

    Thank you Ian,

    Meanwhile i'll keep trying to make it work.

    Thank you for your help, i'll be waiting your reply

    Regards,

    Phillipe
  • In reply to Ian:

    Hi,

    I think the issue may be down to the input text. The block size for the AES cipher is 16 bytes. So, any input less than this will be padded. If you force the input to be 16 bytes then there is no ambiguity and the encryption by openSSL and decryption by the S7G2 works as expected.

    The input file should contain "Hello world!!!!" (without quotes). Note this is 15 bytes plus NULL terminator so 16 bytes in total.

    The screen shot shows the result of decrypting the output from openSSL.

     

    Please note that I am using a slightly different way of calling the APIs using instances. This is the recommended way of doing this.

     

    Regards,

     

    Ian.

     

     

     

    /* HAL-only entry function */
    #include "hal_data.h"

    uint32_t aes128key[4] = { 0x11111111,0x11111111,0x11111111,0x11111111 };
    uint32_t aes128iv[4] ={ 0x11111111,0x11111111,0x11111111,0x11111111 };

    uint8_t cipher_text[16] BSP_ALIGN_VARIABLE_V2(4) = { 0xbe, 0x23, 0x71, 0x8f, 0x41, 0xc0, 0xf4, 0xb4, 0x80, 0x80, 0x90, 0xeb, 0xb9, 0x87, 0x95, 0xbb };
    uint8_t plain_text[16] BSP_ALIGN_VARIABLE_V2(4);

    void hal_entry(void)
    {
    /* TODO: add your own code here */
    ssp_err_t err;

    err = g_sce.p_api->open(g_sce.p_ctrl, g_sce.p_cfg);
    if (SSP_SUCCESS != err)
    {
    __BKPT(0);
    }

    err = g_sce_aes_0.p_api->open(g_sce_aes_0.p_ctrl, g_sce_aes_0.p_cfg);
    if (SSP_SUCCESS != err)
    {
    __BKPT(0);
    }

    err = g_sce_aes_0.p_api->decrypt(g_sce_aes_0.p_ctrl, aes128key, aes128iv, (sizeof(cipher_text) / 4), (uint32_t *)cipher_text, (uint32_t *)plain_text);
    if (SSP_SUCCESS != err)
    {
    __BKPT(0);
    }

    while(1)
    {
    R_BSP_SoftwareDelay(100, BSP_DELAY_UNITS_MILLISECONDS);
    }
    }

  • In reply to Ian:

    A correction to my previous post. OpenSSL is applying padding to the 15 byte text bytes which is why there is a 1 at the end of the decrypted message. OpenSSL uses PKCS#5 as the default padding scheme. If the message is exactly 16 bytes and padding enabled then an additional 16 bytes of cipher text are produced.

    Regards,

    Ian.
  • In reply to Ian:

     

     

    Hi Ian,

    First of all, thank you very much for your reply and example.

    I tried to replicate what you did , however i could not get the same result.

    I created a project and  copied and pasted the code that you provided.

    The result that i got was different from yours. You can see from the first print that in the plain_text buffer the message is not "Hello world!!!!"

    The only change that i've made was to use the macro BSP_ALIGN_VARIABLE(4) instead of BSP_ALIGN_VARIABLE_V2(4) because there was no such macro

    on my project

     

    I'm using the ssp 1.3 as you can see on the second print, and don't know if it has any influence on this result.

     

    And finally i couldn't neither generate the same encrypted bytes as you did  using the openssl, would please provide the command that you used.

    I encrypted the file with the message "Hello world!!!!" using the following command:

    enc -nosalt -aes-128-cbc -in file.txt -out file_crypto.txt -K 11111111111111111111111111111111  - iv 11111111111111111111111111111111  

     

     

  • In reply to Phillipe:

    file_encrypt.txt
    �#q�A�����빇��
    Hi,

    This is the openssl command line I used.

    openssl enc -e -nosalt -aes-128-cbc -in C:\Users\b3800274\Downloads\file.txt -out file_encrypt.txt -K 11111111111111111111111111111111 -iv 11111111111111111111111111111111

    I have attached the output file.

    I am using the latest version of the SSP v1.5.3. Can you try with this version? There have been many changes in the SSP since v1.3.0. Having a working 1.5.3 project may help debug your 1.3.0 if you have to stay on that version.

     

    Regards,

     

    Ian.

  • In reply to Ian:

    Hi Ian,

    I updated my ssp version to the 1.5.3 and it worked just like the example that you provided me.

    But now my problem is that i'm trying to encrypt a file that has a size of 3.676.608 bytes and what I do is to read 3072 bytes from the file at a time and decrypt those bytes (3072).

    However what a I realized is that the first 3072 bytes from this file are decrypted correctly and the rest of the file is decrypted wrongly.

    This happens because I read each 3072 bytes from the file and decrypt it until all the file is read.

    I'm not trying to decrypt the whole file at once, because it would be necessary to have a buffer with a size of 3.6MB.

    Is there any work around to decrypt a file of this size ??


    ps; I encrypt the file using the Open SSL

    Kind regards,

    Phillipe
  • In reply to Phillipe:

    Hi,

    Are you reinitialising the IV on the second decrypt operation? The IV should only be set at the beginning of the first decrypt. Are you passing a pointer to a variable containing the IV or hard coding it?

    Regards,

    Ian.
  • In reply to Ian:

    Hi Ian,

    Thank you very much , the problem was indeed the reinitialising of the IV on the second decrypt operation.

    I fix that and now the decryption process works fine.

    I just have one final question :

    When I was trying to replicate your example of decrypting the message "Hello world!!!!" I was failing until I

    changed the ssp version from 1.3.0 to 1.5.3.

    So my question is :

    Was there any changes on the decryption API from the ssp version 1.3.0 to 1.5.3 ?

    I thought the encryption/decryption process would be the same , no matter what SSP version I use.

    Kind Regards,

    Phillipe
  • In reply to Phillipe:

    Hi,

    I am pleased you have everything working now. There have been several SSP releases between 1.3.0 and 1.5.3 each one adding features and fixing issues. So, it is quite possible the decryption API functionality has been subject to change. To find out exactly what has changed it would be necessary to download the release notes for each release and search for the SCE module in each one.

    Regards,

    Ian.
  • In reply to Ian:

    Hi,

    I'm sorry to ask again but i changed the key on openssl to

    - K 1234567811111111111111111111111111111111 -iv 11111111111111111111111111111111

    and then i set the buffer on my code to :

    uint32_t aes128key[4] = { 0x11111111,0x11111111,0x11111111,0x12345678 };
    uint32_t aes128iv[4] ={ 0x11111111,0x11111111,0x11111111,0x11111111 };

    However It didn't decrypt correctly.

    I also try setting the aes128key[4] like this

    uint32_t aes128key[4] = { 0x12345678,0x11111111,0x11111111,0x11111111 };

    and also didn't work.

    When i use the key 11111111111111111111111111111111 works fine but if i changed the key the process failed.

    I'm sure is something about how to set the aes128key , but i didn't find any reference about it.


    Kind regards,

    Phillipe