LoginSignup
3
7

More than 1 year has passed since last update.

SwiftでAES暗号化/復号化

Last updated at Posted at 2019-07-28

環境

  • Xcode 10.3
  • Swift 5.0.1

AES/CBC/PKCS7Padding してみる

IDZSwiftCommonCrypto というフレームワークを利用する。 CommonCrypto の Swift ラッパー。

CocoaPods または Carthage が利用できる。 CocoaPods の場合、自分の環境ではREADMEに記載されているようにバージョン番号を併記するとうまくいかず、バージョン番号ははずした。

platform :ios, '9.0'

target 'HogeApp' do
  use_frameworks!

  pod 'IDZSwiftCommonCrypto'
end
import IDZSwiftCommonCrypto

class CryptUtil {
    // 暗号化
    class func encrypt(plainText: String, key: String, iv: String) -> [UInt8] {
        let cryptor = Cryptor(operation: .encrypt, algorithm: .aes, options: .PKCS7Padding, key: key, iv: iv)
        if let cipheredText = cryptor.update(plainText)?.final() {
            return cipheredText
        }
        return []
    }

    // 復号化
    class func decrypt(encryptedData: [UInt8], key: String, iv: String) -> String? {
        let cryptor = Cryptor(operation: .decrypt, algorithm: .aes, options: .PKCS7Padding, key: key, iv: iv)
        if let decryptedBytes = cryptor.update(encryptedData)?.final() {
            return String(bytes: decryptedBytes, encoding: .utf8)
        }
        return nil
    }
}

検索すると CryptoSwift がよくかかるが、こちらはちょっと細工しないとパフォーマンスが出ないのと、もともと開発者自身の学習用だったという事もあって、 IDZSwiftCommonCrypto のほうを利用してみた。

ちなみに PKCS5Padding と PKCS7Padding は互換性があるという事で、 PKCS5Padding したデータも問題なく扱う事ができた。

SHA256 してみる

これも IDZSwiftCommonCrypto でできる。

extension String {
    func sha256() -> [UInt8] {
        return Digest(algorithm: .sha256).update(self)?.final() ?? []
    }
}

[UInt8] を hex string に変換する

ダンプする時によく使うので。

extension Collection where Element == UInt8 {
    var hexa: String {
        return map{ String(format: "%02X", $0) }.joined()
    }
}

参考

3
7
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
7