Apple has released a swift-based CryptoKit framework for WWDC2019 that makes it easier to generate hash values, encrypt/decrypt data, sign digital signatures, and negotiate keys.

Before reading this article, it is necessary to have some basic knowledge of cryptography. Please refer to the previous article on The Basics of Cryptography.

Hash value

  • Three Hash functions are provided:

    • SHA256
    • SHA384
    • SHA512
  • Hash plain Data of type Data

    let str = “Hello CryptoKit” let data = str.data(using: .utf8)!

    let hash256 = SHA256.hash(data: data) let hash384 = SHA384.hash(data: data) let hash512 = SHA512.hash(data: data)

    Print (hash256.description) copy the code

  • Hash file

    if let filePath = Bundle.main.path(forResource: “secret”, ofType: “json”), let data = FileManager.default.contents(atPath: filePath) {

    let hash256 = SHA256.hash(data: data)
    let hash384 = SHA384.hash(data: data)
    let hash512 = SHA512.hash(data: data)
    
    print(hash256.description)
    Copy the code

    } copy code

HMAC

HMAC can be understood as a more secure Hash that requires the help of the previous Hash function.

Let salt = "YungFan".data(using:.utf8)! Let key = SymmetricKey(size: .bits256) // HMAC with SHA256 let authenticationCode = HMAC<SHA256>.authenticationCode(for: salt, using: Key) print (authenticationCode) / / verification if HMAC < SHA256 >. IsValidAuthenticationCode (Data (authenticationCode), Authenticating: salt, using: key) {print(" untampered ")} Copy the codeCopy the code

Encrypting and Encrypting Data

Support aes-GCM and ChaChaPoly algorithms. ChaChaChaPoly was preferred for development because it is officially faster on mobile devices. The core concept of ChaChaChaPoly is ChaChaChaPoly.SealedBox, which can be understood as a data container that can only be accessed through a key. The encrypted ciphertext is placed in the data container during the encryption operation, and the ciphertext needs to be extracted for decryption during the decryption operation.

  • encryption

    // let STR = “Hello CryptoKit” let data = str.data(using:.utf8)!

    Let key128 = SymmetricKey(size:.bits128) let key192 = SymmetricKey(size:.bits128) .bits192) let key256 = SymmetricKey(size: .bits256)

    // Let encryptedContent = try? Chachapoly.seal (data, using: key256).combined

  • decryption

    If encryptedContent = encryptedContent {if let sealedBox = try? ChaChaPoly.SealedBox(combined: encryptedContent) { if let decryptedContent = try? ChaChaPoly.open(sealedBox, using: key256) { print(String(data: decryptedContent, encoding: .utf8)) }

    Let nonce = SealedBox. Nonce let CipherText = SealedBox. Ciphertext let Tag = SealedBox print(sealedBox.combined == nonce + ciphertext + tag) }Copy the code

    } copy code

A digital signature

Curve25519, P521, P384, and P256 are built in to create and verify encrypted signatures. The different types have different security and speed, but Curve25519 is usually chosen. 563513413, no matter you are big ox or small white welcome to enter

  • Generate a public/private key

    / / private key let privateKey = Curve25519. Signing the privateKey () / / public key let publicKey = privateKey. PublicKey / / release the public key PublicKeyData = publicKey rawRepresentation duplicate code

  • The private key signature

    let str = “Hello CryptoKit” let data = str.data(using: .utf8)!

    let signature = try? Privatekey.signature (for: data) copies the code

  • A public key to verify

    if let signature = signature { if publicKey.isValidSignature(NSData(data: signature) , for: Data) {print(” valid signature “)}} Copy the code

Key agreement

Key negotiation is a process through which two communication parties can securely select an encryption key and then use it to encrypt and decrypt data.

Let salt = "YungFan".data(using:.utf8)! / / the user A and user B will generate A pair of public and private keys let privateKeyA = P521. KeyAgreement. PrivateKey () let publicKeyA = privateKeyA. PublicKey let PrivateKeyB = P521. KeyAgreement. PrivateKey () let publicKeyB = privateKeyB. PublicKey / / the user with A private key and user B's public key to create A Shared key let sharedSecretA = try? privateKeyA.sharedSecretFromKeyAgreement(with: publicKeyB) let symmetricKeyA = sharedSecretA? .hkdfDerivedSymmetricKey(using: SHA256.self, salt: salt, sharedInfo: Data(), outputByteCount: 32) user B uses the private key and user A's public key to create A shared key. privateKeyB.sharedSecretFromKeyAgreement(with: publicKeyA) let symmetricKeyB = sharedSecretB? .hkdfDerivedSymmetricKey(using: SHA256.self, salt: salt, sharedInfo: Data(), outputByteCount: 32) if symmetricKeyA == symmetricKeyB {print("A and B have A shared key ")}Copy the code