I'm new to iOS and I don't have idea about how to encrypt string using AES 256 with ECB mode and padding I take look of cryptoswift but I get error of key length I have 64 character key and I'm not able to encrypt
func aes_Encrypt(AES_KEY: String) -> String {
var result = ""
do {
let key: [UInt8] = Array(AES_KEY.utf8) as [UInt8]
let aes = try! AES(key: key, blockMode: ECB() as BlockMode, padding: .pkcs5)
let encrypted = try aes.encrypt(Array(self.utf8))
result = encrypted.toHexString()
print("AES Encryption Result: \(result)")
} catch {
print("Error: \(error)")
}
return result
}
64 characters × 8 bits = 512 bits, not the 256 required for AES256.
If the string you are passing in is a hexadecimal representation of a key (e.g. "1234abcd…"), you will need to break it into a sequence of two-character substrings and use UInt8(…, radix:16) to parse each one as hexadecimal.
Related
I am using CryptoSwift 1.4.1, iOS 15.2, PyCryptodome 3.12.0, and XCode 13.2.1 to encrypt small string messages that I send to a Raspberry Pi Linux Device over BLE. It works when iOS encrypts the message and sends it to the Raspberry Pi. The Pi can successfully decrypt it. Now I want to do the inverse, encrypt a message on the Pi and have the iOS App read and decrypt it. This, however is not working and the decrypted value is the not the message I encrypted on the Pi.
Working iOS encryption:
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()
}
let ivString = "4198816658388141"
let keyString = "9004786896524916"
let key = [UInt8](keyString.utf8)
let iv = [UInt8](ivString.utf8)
let encryptedSsid = try! aesEncrypt(stringToEncrypt: ssid!, key: key, iv: iv)
Working Raspberry Pi decryption in Python:
KEY = b'9004786896524916'
IV = b'4198816658388141'
MODE = AES.MODE_CFB
def decrypt(key, iv, encrypted_text):
logger.info(f"Encrypted: {encrypted_text}")
aes = AES.new(key, MODE, iv, segment_size=128)
encrypted_text_bytes = binascii.a2b_hex(encrypted_text)
decrypted_text = aes.decrypt(encrypted_text_bytes).decode("utf-8")
logger.info(f"Decrypted: {decrypted_text}")
return decrypted_text
I tried to encrypt a message on the Pi with the following code:
KEY = b'9004786896524916'
IV = b'4198816658388141'
MODE = AES.MODE_CFB
def encrypt(key, decrypted_text):
# Create cipher object and encrypt the data
logger.info(f"Decrypted: {decrypted_text}")
cipher = AES.new(key, MODE, segment_size=128) # Create a AES cipher object with the key using the mode CBC
#encrypted_text = cipher.encrypt(pad(decrypted_text, AES.block_size)) # Pad the input data and then encrypt
encrypted_text = cipher.encrypt(decrypted_text) # Pad the input data and then encrypt
logger.info(f"Encrypted: {encrypted_text}")
return encrypted_text
...
encrypt(KEY, returnString('utf-8'))
However, the iOS App fails to decrypt it properly with this method:
func aesDecrypt(stringToDecrypt: String, key: Array<UInt8>, iv: Array<UInt8>) throws -> String {
let data = stringToDecrypt.data(using: String.Encoding.utf8)
let decrypted = try AES(key: key, blockMode: CFB(iv: iv), padding: .noPadding).decrypt((data?.bytes)!)
return decrypted.toHexString()
}
let ivString = "4198816658388141"
let keyString = "9004786896524916"
let key = [UInt8](keyString.utf8)
let iv = [UInt8](ivString.utf8)
var message = try! aesDecrypt(stringToDecrypt: charString, key: key, iv: iv)
How can I get decryption to work properly in the iOS App when a message is encrypted on the Pi?
In the encrypt() method the IV is not considered. As in aesEncrypt(), the IV must be passed and used when creating the AES object.
Furthermore there are bugs in the encoding: The plaintext must be UTF8 encoded and the ciphertext must be hex encoded:
from Crypto.Cipher import AES
import binascii
def encrypt(key, iv, plaintext):
cipher = AES.new(key, MODE, iv, segment_size=128)
plaintext_bytes = plaintext.encode("utf-8")
ciphertext = cipher.encrypt(plaintext_bytes)
ciphertext_hex = binascii.b2a_hex(ciphertext)
return ciphertext_hex
This function is the counterpart to decrypt(), i.e. encrypt() can be used to generate a ciphertext which can be decrypted with decrypt() (or aesDecrypt()).
In the iOS code there are two bugs, both concerning the encoding: The ciphertext must not be UTF8 encoded, but hex decoded. And the decrypted data must not be hex encoded, but UTF-8 decoded.
A possible fix is:
func aesDecrypt(stringToDecrypt: String, key: Array<UInt8>, iv: Array<UInt8>) throws -> String {
let data = Array<UInt8>(hex: stringToDecrypt)
let decrypted = try AES(key: key, blockMode: CFB(iv: iv), padding: .noPadding).decrypt(data)
return String(bytes: decrypted, encoding: .utf8)!
}
This function is the counterpart to aesEncrypt(), i.e. aesDecrypt() can be used to decrypt a ciphertext generated with aesEncrypt() (or encrypt()).
Regarding security: A static IV is insecure. Instead, the IV should be randomly generated for each encryption. Since the (non-secret IV) is needed for decryption, it is passed along with the ciphertext (typically concatenated).
I'm working on a data manager for a friend who stores client info on his computer. The info is public record, so top security isn't a big deal (he currently stores it in plain text), but he wouldn't mind having some sort of encryption. Without going into full detail of the program, I'll have to over-simplify my question...
If I want to encrypt a text object or a picture object, and lock it with a password before writing to the disk, what is my best option? I plan to implement this for macOS as well as iOS so he can send and share the files to anyone/any device. So for iOS, speed would be a good thing, and keeping the file size down is good for mobile data usage.
I'm new to Apple Development, so I'm still sifting through APIs and frameworks to learn everything, so I apologize for asking what is probably an easy question. It's also finals week, so I only work on this in my spare time and a bit of help is always appreciated.
Thanks!
-Sanders
Symmetric encryption is used to encrypt data and AES (Advanced Encryption Standard) is the current standard. Apple provides Common Crypto in the Security.framework and is fast using applicable OSX instructions and hardware encryption on iOS. Additionally store the key in the Keychain.
Example from deprecated documentation section:
AES encryption in CBC mode with a random IV (Swift 3+)
The iv is prefixed to the encrypted data
aesCBC128Encrypt will create a random IV and prefixed to the encrypted code.
aesCBC128Decrypt will use the prefixed IV during decryption.
Inputs are the data and key are Data objects. If an encoded form such as Base64 if required convert to and/or from in the calling method.
The key should be exactly 128-bits (16-bytes), 192-bits (24-bytes) or 256-bits (32-bytes) in length. If another key size is used an error will be thrown.
PKCS#7 padding is set by default.
This example requires Common Crypto
It is necessary to have a bridging header to the project:
#import <CommonCrypto/CommonCrypto.h>
Add the Security.framework to the project.
This is example, not production code.
enum AESError: Error {
case KeyError((String, Int))
case IVError((String, Int))
case CryptorError((String, Int))
}
// The iv is prefixed to the encrypted data
func aesCBCEncrypt(data:Data, keyData:Data) throws -> Data {
let keyLength = keyData.count
let validKeyLengths = [kCCKeySizeAES128, kCCKeySizeAES192, kCCKeySizeAES256]
if (validKeyLengths.contains(keyLength) == false) {
throw AESError.KeyError(("Invalid key length", keyLength))
}
let ivSize = kCCBlockSizeAES128;
let cryptLength = size_t(ivSize + data.count + kCCBlockSizeAES128)
var cryptData = Data(count:cryptLength)
let status = cryptData.withUnsafeMutableBytes {ivBytes in
SecRandomCopyBytes(kSecRandomDefault, kCCBlockSizeAES128, ivBytes)
}
if (status != 0) {
throw AESError.IVError(("IV generation failed", Int(status)))
}
var numBytesEncrypted :size_t = 0
let options = CCOptions(kCCOptionPKCS7Padding)
let cryptStatus = cryptData.withUnsafeMutableBytes {cryptBytes in
data.withUnsafeBytes {dataBytes in
keyData.withUnsafeBytes {keyBytes in
CCCrypt(CCOperation(kCCEncrypt),
CCAlgorithm(kCCAlgorithmAES),
options,
keyBytes, keyLength,
cryptBytes,
dataBytes, data.count,
cryptBytes+kCCBlockSizeAES128, cryptLength,
&numBytesEncrypted)
}
}
}
if UInt32(cryptStatus) == UInt32(kCCSuccess) {
cryptData.count = numBytesEncrypted + ivSize
}
else {
throw AESError.CryptorError(("Encryption failed", Int(cryptStatus)))
}
return cryptData;
}
// The iv is prefixed to the encrypted data
func aesCBCDecrypt(data:Data, keyData:Data) throws -> Data? {
let keyLength = keyData.count
let validKeyLengths = [kCCKeySizeAES128, kCCKeySizeAES192, kCCKeySizeAES256]
if (validKeyLengths.contains(keyLength) == false) {
throw AESError.KeyError(("Invalid key length", keyLength))
}
let ivSize = kCCBlockSizeAES128;
let clearLength = size_t(data.count - ivSize)
var clearData = Data(count:clearLength)
var numBytesDecrypted :size_t = 0
let options = CCOptions(kCCOptionPKCS7Padding)
let cryptStatus = clearData.withUnsafeMutableBytes {cryptBytes in
data.withUnsafeBytes {dataBytes in
keyData.withUnsafeBytes {keyBytes in
CCCrypt(CCOperation(kCCDecrypt),
CCAlgorithm(kCCAlgorithmAES128),
options,
keyBytes, keyLength,
dataBytes,
dataBytes+kCCBlockSizeAES128, clearLength,
cryptBytes, clearLength,
&numBytesDecrypted)
}
}
}
if UInt32(cryptStatus) == UInt32(kCCSuccess) {
clearData.count = numBytesDecrypted
}
else {
throw AESError.CryptorError(("Decryption failed", Int(cryptStatus)))
}
return clearData;
}
Example usage:
let clearData = "clearData0123456".data(using:String.Encoding.utf8)!
let keyData = "keyData890123456".data(using:String.Encoding.utf8)!
print("clearData: \(clearData as NSData)")
print("keyData: \(keyData as NSData)")
var cryptData :Data?
do {
cryptData = try aesCBCEncrypt(data:clearData, keyData:keyData)
print("cryptData: \(cryptData! as NSData)")
}
catch (let status) {
print("Error aesCBCEncrypt: \(status)")
}
let decryptData :Data?
do {
let decryptData = try aesCBCDecrypt(data:cryptData!, keyData:keyData)
print("decryptData: \(decryptData! as NSData)")
}
catch (let status) {
print("Error aesCBCDecrypt: \(status)")
}
Example Output:
clearData: <636c6561 72446174 61303132 33343536>
keyData: <6b657944 61746138 39303132 33343536>
cryptData: <92c57393 f454d959 5a4d158f 6e1cd3e7 77986ee9 b2970f49 2bafcf1a 8ee9d51a bde49c31 d7780256 71837a61 60fa4be0>
decryptData: <636c6561 72446174 61303132 33343536>
Notes:
One typical problem with CBC mode example code is that it leaves the creation and sharing of the random IV to the user. This example includes generation of the IV, prefixed the encrypted data and uses the prefixed IV during decryption. This frees the casual user from the details that are necessary for CBC mode.
For security the encrypted data also should have authentication, this example code does not provide that in order to be small and allow better interoperability for other platforms.
Also missing is key derivation of the key from a password, it is suggested that PBKDF2 be used is text passwords are used as keying material.
For robust production ready multi-platform encryption code see RNCryptor.
Also consider RNCryptor for a complete implementation including password derivation, encryption authentication and versioning.
Note passwords and keys:
There is a difference between passwords and keys. AES encryption keys are exactly one of 3 lengths: 128, 192 or 256 bits and should appear to be random bits. Passwords/passphrases are human readable text. When passwords are used the encryption key needs to be derived from it, the there are functions to achieve this such as PBKDF2 (Password Based Key Derivation Function 2). RNCryptor includes such a derivation function.
Password Based Key Derivation 2 (Swift 3+)
Password Based Key Derivation can be used both for deriving an encryption key from password text and saving a password for authentication purposes.
There are several hash algorithms that can be used including SHA1, SHA256, SHA512 which are provided by this example code.
The rounds parameter is used to make the calculation slow so that an attacker will have to spend substantial time on each attempt. Typical delay values fall in the 100ms to 500ms, shorter values can be used if there is unacceptable performance.
This example requires Common Crypto
It is necessary to have a bridging header to the project:
#import <CommonCrypto/CommonCrypto.h>
Add the Security.framework to the project.
Parameters:
password password String
salt salt Data
keyByteCount number of key bytes to generate
rounds Iteration rounds
returns Derived key
func pbkdf2SHA1(password: String, salt: Data, keyByteCount: Int, rounds: Int) -> Data? {
return pbkdf2(hash:CCPBKDFAlgorithm(kCCPRFHmacAlgSHA1), password:password, salt:salt, keyByteCount:keyByteCount, rounds:rounds)
}
func pbkdf2SHA256(password: String, salt: Data, keyByteCount: Int, rounds: Int) -> Data? {
return pbkdf2(hash:CCPBKDFAlgorithm(kCCPRFHmacAlgSHA256), password:password, salt:salt, keyByteCount:keyByteCount, rounds:rounds)
}
func pbkdf2SHA512(password: String, salt: Data, keyByteCount: Int, rounds: Int) -> Data? {
return pbkdf2(hash:CCPBKDFAlgorithm(kCCPRFHmacAlgSHA512), password:password, salt:salt, keyByteCount:keyByteCount, rounds:rounds)
}
func pbkdf2(hash :CCPBKDFAlgorithm, password: String, salt: Data, keyByteCount: Int, rounds: Int) -> Data? {
let passwordData = password.data(using:String.Encoding.utf8)!
var derivedKeyData = Data(repeating:0, count:keyByteCount)
let derivationStatus = derivedKeyData.withUnsafeMutableBytes {derivedKeyBytes in
salt.withUnsafeBytes { saltBytes in
CCKeyDerivationPBKDF(
CCPBKDFAlgorithm(kCCPBKDF2),
password, passwordData.count,
saltBytes, salt.count,
hash,
UInt32(rounds),
derivedKeyBytes, derivedKeyData.count)
}
}
if (derivationStatus != 0) {
print("Error: \(derivationStatus)")
return nil;
}
return derivedKeyData
}
Example usage:
let password = "password"
//let salt = "saltData".data(using: String.Encoding.utf8)!
let salt = Data(bytes: [0x73, 0x61, 0x6c, 0x74, 0x44, 0x61, 0x74, 0x61])
let keyByteCount = 16
let rounds = 100000
let derivedKey = pbkdf2SHA1(password:password, salt:salt, keyByteCount:keyByteCount, rounds:rounds)
print("derivedKey (SHA1): \(derivedKey! as NSData)")
Example Output:
derivedKey (SHA1): <6b9d4fa3 0385d128 f6d196ee 3f1d6dbf>
(Xcode 8, Swift 3)
Using the CryptoSwift library, I am wanting to encrypt a string and store it in coredata, for some reason, cipherstring results as nil, despite ciphertext having 128 values:
let aes = try AES(key: pw, iv: nil, blockMode: .CBC, padding: PKCS7())
let ciphertext = try aes.encrypt(token.utf8.map({$0}))
let cipherstring = String(bytes:ciphertext, encoding: String.Encoding.utf8) // always nil
I have also tried using the data: overload of string, convering the byte array to a data object. This also results as nil.
EDIT/SOLUTION (per Rob Napier's answer)
// encode/convert to string
let aes = try AES(key: pw, iv: nil, blockMode: .CBC, padding: PKCS7())
let ciphertext = try aes.encrypt(token.utf8.map({$0}))
let cipherstring = Data(bytes: ciphertext).base64EncodedString()
// decode
let aes = try AES(key: pw, iv: nil, blockMode: .CBC, padding: PKCS7())
let cipherdata = Data(base64Encoded: cipherstring)
let ciphertext = try aes.decrypt(cipherdata!.bytes)
let token = String(bytes:ciphertext, encoding:String.Encoding.utf8)
AES encrypted data is a random bunch of bytes. If you pick a random bunch of bytes, it is very unlikely to be valid UTF-8. If you have data and you want a string, you need to encode the data somehow. The most popular way to do that is Base-64. See Data.base64EncodedString() for a tool to do that. You'll also need Data(base64Encoded:) to reconstruct your Data from the String later.
Is there a way to convert a hexadecimal string to base64 in Swift? For example, I would like to convert:
BA5E64C0DE
to:
ul5kwN4=
It's possible to convert a normal string to base64 by using:
let hex: String = "BA5E64C0DE"
let utf8str: NSData = hex.dataUsingEncoding(NSUTF8StringEncoding)!
let base64Encoded: NSString = utf8str.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
let base64: String = (base64Encoded as String)
But this would give a result of:
QkE1RTY0QzBERQ==
Because it's just treating the hex as a normal UTF-8 String, and not hexadecimal.
It's possible to convert it to base64 correctly by looping through every six hex characters and converting it to it's four respective base64 characters, but this would be highly inefficient, and is just plain stupid (there would need to be 17,830,160 if statements):
if(hex == "000000"){base64+="AAAA"}
else if(hex == "000001"){base64+="AAAB"}
else if(hex == "000002"){base64+="AAAC"}
else if(hex == "BA5E64"){base64+="ul5k"}
//...
It would be nice if there was something like this:
let hex: String = "BA5E64C0DE"
let data: NSData = hex.dataUsingEncoding(NSHexadecimalEncoding)!
let base64Encoded: NSString = data.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
let base64: String = (base64Encoded as String)
But sadly, there's no NSHexadecimalEncoding. Is there any efficient way to convert a hexadecimal string to it's base64 representation in Swift?
The base-64 string, "ul5kwN4=", translates to a binary NSData consisting of of five bytes BA, 5E, 64, C0, and DE.
Now, if you really had a string with the hexadecimal representation, you could convert it to a binary NSData using a routine like the one here: https://stackoverflow.com/a/26502285/1271826
Once you have a NSData, you could build your base 64 string:
let hexString = "BA5E64C0DE"
let binaryData = hexString.dataFromHexadecimalString()
let base64String = binaryData?.base64EncodedStringWithOptions(nil)
That generates the desired output, ul5kwN4=.
First, convert Hex String to Data using the following routine. (Worked in Swift 3.0.2)
extension String {
/// Expanded encoding
///
/// - bytesHexLiteral: Hex string of bytes
/// - base64: Base64 string
enum ExpandedEncoding {
/// Hex string of bytes
case bytesHexLiteral
/// Base64 string
case base64
}
/// Convert to `Data` with expanded encoding
///
/// - Parameter encoding: Expanded encoding
/// - Returns: data
func data(using encoding: ExpandedEncoding) -> Data? {
switch encoding {
case .bytesHexLiteral:
guard self.characters.count % 2 == 0 else { return nil }
var data = Data()
var byteLiteral = ""
for (index, character) in self.characters.enumerated() {
if index % 2 == 0 {
byteLiteral = String(character)
} else {
byteLiteral.append(character)
guard let byte = UInt8(byteLiteral, radix: 16) else { return nil }
data.append(byte)
}
}
return data
case .base64:
return Data(base64Encoded: self)
}
}
}
Then, convert Data to Base64 String using Data.base64EncodedString(options:).
Usage
let base64 = "BA5E64C0DE".data(using: .bytesHexLiteral)?.base64EncodedString()
if let base64 = base64 {
print(base64)
// Prints "ul5kwN4="
}
Got a problem with crypting password with 3DES + ECB algo.
Here is the code I using:
class func encryptPassword(pass: String) -> String {
let keyString = "123456789012345678901234"
let keyData: NSData! = (keyString as NSString).dataUsingEncoding(NSUTF8StringEncoding) as NSData!
let keyBytes = UnsafePointer<UInt8>(keyData.bytes)
let data: NSData! = (pass as NSString).dataUsingEncoding(NSUTF8StringEncoding) as NSData!
let dataLength = UInt(data.length)
let dataBytes = UnsafePointer<UInt8>(data.bytes)
var cryptData = NSMutableData(length: Int(dataLength) + kCCBlockSize3DES)!
var cryptPointer = UnsafeMutablePointer<UInt8>(cryptData.mutableBytes)
var cryptLength = size_t(cryptData.length)
let keyLength = size_t(kCCKeySize3DES)
let operation: CCOperation = UInt32(kCCEncrypt)
let algoritm: CCAlgorithm = UInt32(kCCAlgorithm3DES)
let options: CCOptions = UInt32(kCCOptionECBMode | kCCOptionPKCS7Padding)
var numBytesEncrypted :UInt = 0
var cryptStatus = CCCrypt(operation,
algoritm,
options,
keyBytes, keyLength,
nil,
dataBytes, dataLength,
cryptPointer, cryptLength,
&numBytesEncrypted)
var base64cryptString = ""
if UInt32(cryptStatus) == UInt32(kCCSuccess) {
let x: UInt = numBytesEncrypted
cryptData.length = Int(numBytesEncrypted)
println("cryptLength = \(numBytesEncrypted),\n cryptData = \(cryptData)\n")
base64cryptString = cryptData.base64EncodedStringWithOptions(nil)
} else {
println("Error: \(cryptStatus)")
}
return base64cryptString
}
}
That works, but failed verifying. I used online-encryptor for that like http://www.tools4noobs.com/online_tools/encrypt/
Select TripleDES and ECB
For code
let encrypted = Utils.encryptPassword("123456789")
Console shows
cryptData = <1dd50935 b702084b d164ce3e 9427c493>
Online converter shows
1dd50935b702084bf9fbee67c9643874
i.e first 8 bytes are correct but the last ones - not. How could be that? What could be wrong with code?
=========== EDIT ============
As #Artjom said - there is should be zeroes values added to complete block.
This code in start adds zero values:
// Trim password
var password = pass.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
// Adding null padding
let count = 8 - countElements(password) % 8
for i in 1...count {
password += "\0"
}
Then use "password" var instead incoming "pass" to generate "data"
And also remove Padding for options
let algoritm: CCAlgorithm = UInt32(kCCAlgorithm3DES)
Thanks
It is probably a different padding being used. DES has a block size of 8 byte. So the first block is 12345678 and the second block is 9. Since DES is a block cipher the plaintext must be padded to the next block size.
The online tool probably uses zero padding or no padding which basically means that the other bytes of the block are set to 0x00. You use in your code on the other hand PKCS#7 padding. Remove the PKCS#7 flag, to see if the output matches.
You will have to do the zero padding yourself if the library doesn't provide it. Fill up the password with \0 bytes until a multiple of the block size is reached during encryption and remove those zero bytes during decryption.
It is not recommended to use encryption without padding.
Also, password are not usually encrypted, but rather hashed with a random salt and multiple iterations. When your user database gets "lost", you don't want the one who found it, to be able to easily reverse the passwords and log in as any user (the assumption being that the encryption key is also easily "loseable"). Using a strong cryptographic hash function on the other hand has the advantage that it is really infeasible to reverse the hash.