Skip to content

Instantly share code, notes, and snippets.

@asaday
Created August 28, 2018 08:40
Show Gist options
  • Save asaday/2cd18ffdf34673e058723f8b0211fc9a to your computer and use it in GitHub Desktop.
Save asaday/2cd18ffdf34673e058723f8b0211fc9a to your computer and use it in GitHub Desktop.
static let fixkey = Data(bytes: [171, 221, 144, 111, 79, 19, 231, 93, 101, 8, 84, 181, 85, 164, 105, 161]) // 16bytes
static func encrypt(_ value: String) -> Data? {
guard let src = value.data(using: .utf8) else { return nil }
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
fixkey.withUnsafeBytes { keyBytes in
CCCrypt(
CCOperation(kCCEncrypt), CCAlgorithm(kCCAlgorithmAES),
CCOptions(kCCOptionPKCS7Padding | kCCOptionECBMode),
keyBytes, fixkey.count, nil,
srcBytes, src.count,
dstBytes, dstlen, &numBytes)
}
}
}
if cryptStatus != kCCSuccess { return nil }
return dst[0 ..< numBytes]
}
static func decrypt(_ src: Data) -> String? {
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
fixkey.withUnsafeBytes { keyBytes in
CCCrypt(
CCOperation(kCCDecrypt), CCAlgorithm(kCCAlgorithmAES),
CCOptions(kCCOptionPKCS7Padding | kCCOptionECBMode),
keyBytes, fixkey.count, nil,
srcBytes, src.count,
dstBytes, dstlen, &numBytes)
}
}
}
if cryptStatus != kCCSuccess { return nil }
return String(data: dst[0 ..< numBytes], encoding: .utf8)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment