ios应用开发入门教程_cryptokit教程如何在iOS13应用上使用cryptokit

ios应用开发入门教程

In this article, we are going to see an introduction tutorial to CryptoKit,, presented by Apple on WWDC19, and how it can be used in applications developed for iOS13. CryptoKit allows, for example, the exchange of public and private keys, so that you could get to make purchases from an iPhone with the cryptocurrencies (Bitcoin, for example) stored in it.

在本文中,我们将看到Apple在WWDC19上介绍的CryptoKit入门教程,以及如何在为iOS13开发的应用程序中使用它。 例如, CryptoKit允许交换公钥和私钥,这样您就可以从存储有加密货币(例如,比特币)的iPhone上进行购买。

CryptoKit allows developers:

CryptoKit允许开发人员:

  • Create and compare hashes.

    创建并比较哈希。
  • Message encryption and authentication using symmetric cryptography.

    使用对称密码的消息加密和身份验证。
  • Use of public keys to create and evaluate digital signatures.

    使用公钥创建和评估数字签名。

The use of CryptoKit is simple and does not require low level API knowledge or manually memory management.

CryptoKit的使用很简单,不需要底层API知识或手动进行内存管理。

可以使用CryptoKit执行的主要操作 (Main operations that can be performed with CryptoKit)

散列 (Hashing)

Hash functions generate, in general, a unique key from some input data. While the input data is the same, the key obtained will be the same, which allows you to use them, for example, to know if a file has been modified or not (if it has been modified, its hash will be different).CryptoKit allows, through the use of the HashFunction protocol, to obtain a hash according to three different implementations:

通常,哈希函数从某些输入数据中生成唯一键。 当输入数据相同时,获得的密钥将相同,这使您可以使用它们,例如,了解文件是否已被修改(如果已被修改,则其哈希将有所不同)。 CryptoKit允许通过使用HashFunction协议,根据三种不同的实现方式来获取哈希:

  • SHA256

    SHA256
  • SHA384

    SHA3​​84
  • SHA512

    SHA512
let data = string.data(using: .utf8)!
let hash256 = SHA256.hash(data: data)
let hash384 = SHA384.hash(data: data)
let hash512 = SHA512.hash(data: data)

In this way we obtain hash values in a simpler way than in the past:

通过这种方式,我们可以比过去更简单地获取哈希值:

func sha256(stringValue: String) -> String {
  let data = stringValue.data(using: String.Encoding.utf8)!
  var digest = [UInt8](repeating: 0, count: Int(CC_SHA1_DIGEST_LENGTH))
  CC_SHA256((data as NSData).bytes, CC_LONG(data.count), &digest)
  let hexBytes = digest.map { String(format: "%02hhx", $0) }
  return hexBytes.joined(separator: "")
}

Apple also provides access to some algorithms that it considers unsafe, such as MD5 and SHA1, for backward compatibility reasons. For this we must use enum Insecure:

Apple还提供了一些出于向后兼容性原因而认为不安全的算法(例如MD5和SHA1)的访问权限。 为此,我们必须使用枚举Insecure

let md5Hash = Insecure.MD5.hash(data: data)
let sha1Hash = Insecure.SHA1.hash(data: data)

创建和验证数字签名 (Create and validate digital signatures)

Digital signatures are used to verify the authenticity of a message or data. This procedure is done many times daily, either in email, in financial transactions or when accessing https pages.Cryptokit supports four different ways to create and verify digital signatures:

数字签名用于验证消息或数据的真实性。 每天都会通过电子邮件,财务交易或访问https页面多次执行此过程。 Cryptokit支持四种创建和验证数字签名的方式:

  • Curve25519

    曲线25519
  • P521

    P521
  • P384

    P384
  • P256

    P256

To use this system, we first need to generate a public and a private key:

要使用此系统,我们首先需要生成一个公共密钥和一个私有密钥:

let privateKey = P384.Signing.PrivateKey()
let publicKey = privateKey.publicKey
let publicKeyData = publicKey.rawRepresentation

To sign content we use the private key (which also includes the public key) that we have obtained:

为了对内容进行签名,我们使用已获得的私钥(还包括公钥):

if let signature = try? privateKey.signature(for: data) {
  // We can use signature
}

With the public key we can check if the digital signature is valid or not:

使用公共密钥,我们可以检查数字签名是否有效:

if publicKey.isValidSignature(signature, for: data) {
  print("Valid signature")
}

数据加密 (Data encryption)

Nowadays data encryption is of great importance, since it allows your confidentiality. CryptoKit supports two types of encryption algorithms:

如今,数据加密非常重要,因为它可以保护您的机密性。 CryptoKit支持两种类型的加密算法:

  • AES-GCM

    AES-GCM
  • ChaChaPoly (this is preferred in mobile environments because it is faster).

    ChaChaPoly(在移动环境中首选,因为它速度更快)。

We can do the encryption and decryption of data in a simple way:

我们可以通过一种简单的方式对数据进行加密和解密:

// Generates a symetric ramdom key
let randomKey = SymmetricKey(size: .bits256)


// Encrytion
if let cryptedBox = try? ChaChaPoly.seal(data, using: randomKey),
  let sealedBox = try? ChaChaPoly.SealedBox(combined: cryptedBox.combined) {
   // Do whatever with cryptedBox
}


// Decryption
if let combinedData = sealedBox.combined,
  let sealedBoxToOpen = try! ChaChaPoly.SealedBox(combined: combinedData),
  let decryptedData = try! ChaChaPoly.open(sealedBox, using: randomKey),
  let decryptedString = String(data: decryptedData, encoding: .utf8) {
   print(decryptedString)
}

In this case, in the data encryption we obtain an object of type ChaChaPoly.SealedBox (which is a data container that can only be accessed with the encryption key). This object includes the combined property, which in turn contains three properties:

在这种情况下,在数据加密中,我们获得了ChaChaPoly.SealedBox类型的对象(这是一个只能使用加密密钥访问的数据容器)。 该对象包括combined属性,而该属性又包含三个属性:

  • nonce: it is an arbitrary number used in data encryption.

    随机数 :它是数据加密中使用的任意数字。

  • ciphertext: are the encrypted data, with the same size as the input data.

    密文 :是加密的数据,其大小与输入数据相同。

  • tag: it is an authentication label and prevents data from being altered without us noticing.

    tag :它是一个身份验证标签,可防止在不通知我们的情况下更改数据。

密钥共享 (Key sharing)

A key agreement protocol is a process during which two parties securely choose a shared encryption key that can be used to sign and encrypt the data they want to share with each other. This also allows unauthorized parties to access the data.

密钥协商协议是一个过程,在此过程中,双方安全地选择一个共享的加密密钥,该密钥可用于对彼此想要共享的数据进行签名和加密。 这也允许未授权方访问数据。

First, we generate a value for the salt, that is, a value that comprises random bits that are used as one of the inputs in a key derivative function. For example, we can get a value as follows:

首先,我们为salt生成一个值,即一个包含随机位的值,该位​​被用作键派生函数中的输入之一。 例如,我们可以得到如下值:

if let salt = "Our Value For Salt".data(using: .utf8) {
    // Derive keys using the salt value
}

Now, both parties can publish and share with each other their public key (user A shares his public key are user B, and vice versa):

现在,双方都可以发布并彼此共享其公共密钥(用户A共享其公共密钥为用户B,反之亦然):

let userAPrivateKey = P521.KeyAgreement.PrivateKey()
let userAPublicKey = userAPrivateKey.publicKey


let userBPrivateKey = P521.KeyAgreement.PrivateKey()
let userBPublicKey = userBPrivateKey.publicKey

Next, user A shares a secret with his private key and the public key of user B. User B must do the same and verify that the keys obtained are the same:

接下来,用户A与他的私钥和用户B的公钥共享一个秘密。用户B必须这样做,并验证获得的密钥是否相同:

if let userASharedSecret = try? userAPrivateKey.sharedSecretFromKeyAgreement(with: userBPublicKey) {
  let userASymmetricKey = userASharedSecret.hkdfDerivedSymmetricKey(using: SHA256.self, salt: salt, sharedInfo: Data(), outputByteCount: 32)
}


if let userBSharedSecret = try? userBPrivateKey.sharedSecretFromKeyAgreement(with: userAPublicKey) {
  let userBSymmetricKey = userBSharedSecret.hkdfDerivedSymmetricKey(using: SHA256.self, salt: salt, sharedInfo: Data(), outputByteCount: 32)
}


if userASymmetricKey == userBSymmetricKey {
  print("Keys are equal. Let's share data.")
}

Now we can use the generated symmetric key to encrypt information as we have seen previously (either through the AES-GCM algorithm or the ChaChaPoly).

现在,我们可以使用生成的对称密钥对信息进行加密,如我们先前所见(通过AES-GCM算法或ChaChaPoly)。

结论 (Conclusion)

Unlike the previous system used in Apple to encrypt information (CommonCrypto), CryptoKit is high level, so it is simple to use. It includes the most common encryption algorithms, as well as the most used operations: hashing, encryption and key sharing.

与Apple先前用于加密信息的系统( CommonCrypto )不同, CryptoKit是高级的,因此使用简单。 它包括最常用的加密算法以及最常用的操作:哈希,加密和密钥共享。

Originally published at https://www.raulferrergarcia.com on February 17, 2020.

最初于 2020年2月17日 发布在 https://www.raulferrergarcia.com

翻译自: https://medium.com/swlh/cryptokit-tutorial-how-to-use-cryptokit-on-ios13-apps-5961019752f5

ios应用开发入门教程

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值