Created
October 23, 2020 18:19
-
-
Save iosdevzone/45456d2911bf2422bc4a6898876ba0ab to your computer and use it in GitHub Desktop.
Demo code for StackOverflow question: https://stackoverflow.com/questions/64477634/cryptoswift-getting-nil-when-using-makeencryptor-for-string-of-less-than-16
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// main.swift | |
// | |
// Created by idz on 10/23/20. | |
// | |
import Foundation | |
import CryptoSwift | |
import CommonCrypto | |
extension String | |
{ | |
func base64Encoded() -> Data? | |
{ | |
self.data(using: .utf8)?.base64EncodedData() | |
} | |
} | |
func enc(plainText: [String], key: [UInt8], iv: [UInt8]) throws -> (cipherText: [UInt8], authenticationTag: [UInt8]?) | |
{ | |
let gcmEnc = GCM(iv: iv, mode: .detached) | |
var enc = try AES(key: key, blockMode: gcmEnc, padding: .noPadding).makeEncryptor() | |
var ciphertext = Array<UInt8>() | |
for txt in plainText { | |
ciphertext += try enc.update(withBytes: Array(txt.utf8)) | |
} | |
ciphertext += try enc.finish() | |
return (ciphertext, gcmEnc.authenticationTag) | |
} | |
func dec(cipherText: [UInt8], authenticationTag: [UInt8]?, key: [UInt8], iv: [UInt8]) throws -> [UInt8]? { | |
let tagLength = authenticationTag?.count ?? 0 | |
let gcmDec = GCM.init(iv: iv, additionalAuthenticatedData: nil, tagLength: tagLength, mode: .detached) | |
gcmDec.authenticationTag = authenticationTag | |
var aesDec = try AES(key: key, blockMode: gcmDec, padding: .noPadding).makeDecryptor() | |
var decData = try aesDec.update(withBytes: cipherText) | |
decData += try aesDec.finish() | |
return decData | |
} | |
func encAndDec(){ | |
do { | |
guard let key = Data.init(base64Encoded: "12345678901234567890123456789012".base64Encoded()!) | |
else { | |
fatalError("Failed to create key") | |
} | |
let iv : Array<UInt8> = [0,0,0,0, | |
0,0,0,0, | |
0,0,0,0] | |
//let arrStr = ["My name is tarun"] // Working | |
let arrStr = ["tarun"] // Not working for this string | |
let (cipherText, authenticationTag) = try enc(plainText: arrStr, key: key.bytes, iv: iv) | |
guard let decrypedPlainText = try dec(cipherText: cipherText, | |
authenticationTag: authenticationTag, key: key.bytes, iv: iv) else { | |
fatalError("Decryption return nil") | |
} | |
guard let decryptedString = String(bytes: decrypedPlainText, encoding: .utf8) else { | |
fatalError("Failed to convert plaintext to string using UTF8 encoding.") | |
} | |
print("Decrypted Plaintext: \(decryptedString)") | |
} | |
catch let e { | |
print("EXCEPTION: \(e)") | |
} | |
} | |
encAndDec() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment