2

I am currently trying to use AES cryptography to encrypt and decrypt a string that always has a length of 9 characters. What I am trying to do is to encrypt the string in swift and then decrypt that encrypted string in python. I am using AES encryption with CryptoSwift and decrypting with PyCryptodome.

This is what my function in swift looks like:

import CryptoSwift
func crypto_testing() {
        print("Cryptography!")

        let ivString = "0000000000000000"
        let keyString = "This is a key123"

        let key = [UInt8](keyString.utf8)
        let iv = [UInt8](ivString.utf8)
        let stringToEncrypt = "123456789"


        let enc = try! aesEncrypt(stringToEncrypt: stringToEncrypt, key: key, iv: iv)
        print("ENCRYPT:",enc)
    }


    func aesEncrypt(stringToEncrypt: String, key: Array<UInt8>, iv: Array<UInt8>) throws -> String {
        let data = stringToEncrypt.data(using: String.Encoding.utf8)
        let encrypted = try AES(key: key, blockMode: CFB(iv: iv), padding: .noPadding).encrypt((data?.bytes)!)
        return encrypted.toHexString() //result
    }

The result I get from running the crypto_testing function is:

Cryptography!
ENCRYPT: 5d02105a49e55d2ff7

Furthermore, this is what my decryption function looks like in python:

import binascii
from Crypto.Cipher import AES

KEY = b'This is a key123'
IV = b'0000000000000000'
MODE = AES.MODE_CFB

def decrypt(key, iv, encrypted_text):
    aes = AES.new(key, MODE, iv)
    encrypted_text_bytes = binascii.a2b_hex(encrypted_text)
    decrypted_text = aes.decrypt(encrypted_text_bytes)
    return decrypted_text

decrypted_text = decrypt(KEY, IV, encrypted_text)
print(decrypted_text)

And the result from plugging in the encrypted message into the decrypt function like so:

>>> decrypt(b'This is a key123', b'0000000000000000', '5d02105a49e55d2ff7')

b'1%\xdc\xc8\xa0\r\xbd\xb8\xf0' 

If anyone has any clue as to what is going wrong here that would be a great help.

  • 2
    The default segment size for CFB in Pycryptodome is 8 bits ([docs](https://pycryptodome.readthedocs.io/en/latest/src/cipher/classic.html#cfb-mode)). Try your Python code with this parameter `segment_size=128` in `AES.new()`. – t.m.adam Aug 02 '19 at 19:11
  • Thank you adam, that fixed my problem perfectly – Drew Loughran Aug 02 '19 at 19:29
  • setting 128 is not for you. You wanted to encrypt 9 characters. My advice uses CTR mode which doesn't require padding. – kelalaka Aug 02 '19 at 19:46

1 Answers1

0

Try this:


let stringToEncrypt = "123456789"

var aes: AES

var encrypted: [UInt8]

do {

aes = try AES(key: key, blockMode: CBC(iv: iv), padding: . noPadding)

 encrypted = try aes.encrypt(stringToEncrypt.bytes)

}

let base64Encypted = encrypted.toBase64()```
Austin Efnor
  • 166
  • 1
  • 2
  • 16
R.B Niranjan
  • 628
  • 1
  • 7
  • 12