Skip to content

Instantly share code, notes, and snippets.

@asaday
Last active February 4, 2019 08:13
Show Gist options
  • Save asaday/0847445d2a4dbf8958fffd5a92e1b51d to your computer and use it in GitHub Desktop.
Save asaday/0847445d2a4dbf8958fffd5a92e1b51d to your computer and use it in GitHub Desktop.
import CommonCrypto
// openssl enc -d -aes-128-cbc -pass pass:hey -base64 -in enc.txt -p
extension Data {
var hexString: String {
return map { String(format: "%02hhx", $0) }.joined()
}
var md5Data: Data {
var hash = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
CC_MD5((self as NSData).bytes, CC_LONG(count), &hash)
return Data(bytes: hash)
}
}
func encrypt(src: Data, password: String) -> String? {
guard let pass = password.data(using: .utf8) else { return nil }
var salt = Data(count: 8)
_ = salt.withUnsafeMutableBytes { mutableBytes in
SecRandomCopyBytes(kSecRandomDefault, 8, mutableBytes)
}
let key = (pass + salt).md5Data
let iv = (key + pass + salt).md5Data
print("key " + key.hexString)
print("iv " + iv.hexString)
print("salt " + salt.hexString)
guard let aes = encryptAES128(src: src, key: key, iv: iv) else { return nil }
let r = "Salted__".data(using: .utf8)! + salt + aes
return r.base64EncodedString(options: .lineLength64Characters)
}
func encryptAES128(src: Data, key: Data, iv: Data) -> Data? {
var dst = Data(count: kCCBlockSizeAES128 + src.count)
let dstlen = dst.count
var numBytes: size_t = 0
let cryptStatus = dst.withUnsafeMutableBytes { dstBytes in
src.withUnsafeBytes { srcBytes in
key.withUnsafeBytes { keyBytes in
iv.withUnsafeBytes { ivBytes in
CCCrypt(CCOperation(kCCEncrypt), CCAlgorithm(kCCAlgorithmAES),
CCOptions(kCCOptionPKCS7Padding),
keyBytes, key.count, ivBytes,
srcBytes, src.count,
dstBytes, dstlen, &numBytes)
}
}
}
}
if cryptStatus != kCCSuccess { return nil }
return dst[0 ..< numBytes]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment