0

I want to do ECB mode encryption of AES algorithm. I have used CryptoSwift.

I want to do encryption with ECB mode, key size 64 bits (random key) & no padding. I have tried the following code but it is returned at AES instance.

Anyone can help me out?

func aesEncryption() {
    func generateRandomString(length: Int) -> String {
           let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
           return String((0..<length).map{ _ in letters.randomElement()! })
    }
    /* Generate a random key */
    let key = generateRandomString(length: 64)

    /* AES cryptor instance */
    guard let aes = try? AES(key: Array(key.utf8), blockMode: ECB(), padding: .noPadding) else { return }

    /* Encrypt Data */
    let inputData = "Hello CryptoSwift".data(using: .utf8)
    guard let encryptedBytes = try? aes.encrypt(inputData!.bytes) else { return }
    let encryptedData = Data(encryptedBytes)
    print("encryptedData", encryptedData)

    /* Decrypt Data */
    guard let decryptedBytes = try? aes.decrypt(encryptedData.bytes) else { return }
    let decryptedData = Data(decryptedBytes)
    print("decryptedData", String(decoding: decryptedData, as: UTF8.self))
}

My code is working with 32-bit key length & pkcs7 padding. But I don't want that. I want do to it with 64-bit key length & no padding. Below is the working code:

    /* Generate a random key */
    let key = generateRandomString(length: 32)

    /* AES cryptor instance */
    guard let aes = try? AES(key: Array(key.utf8), blockMode: ECB(), padding: .pkcs7) else { return }
Komal Goyani
  • 779
  • 6
  • 25
  • 1
    AES allows 3 key sizes: 16 (for AES-128), 24 (for AES-192) and 32 bytes (for AES-256), so 64 bytes is not possible (by the way, you seem to confuse bits and bytes regarding the key size). ECB is a block cipher mode, i.e. the plaintext must be an integer multiple of the block size (16 bytes for AES), otherwise padding must be used. Your plaintext is 17 bytes long and therefore needs a padding. – Topaco Apr 28 '23 at 07:50
  • 1
    By the way, a key should be a random byte sequence, i.e. your key derivation is a vulnerability. If you want to use a password instead of a key, then you should consider using a reliable key derivation function like PBKDF2. Note that the ECB mode is insecure. – Topaco Apr 28 '23 at 07:53
  • Maybe you should use ChatGPT or something to ask questions to because you don't seem to get Internet search. There is an AES example on [the CryptoSwift](https://cryptoswift.io/) website. But if you want to use 64 bit AES, ECB and nopadding for regular message, *I propose you study cryptography first*. – Maarten Bodewes Apr 28 '23 at 09:10

0 Answers0