Create Apple Watch App

This commit is contained in:
Christoph Hagen
2023-08-07 15:57:09 +02:00
parent 9b14f442b0
commit f599cb790b
14 changed files with 620 additions and 5 deletions

View File

@ -46,3 +46,26 @@ extension String {
return results.map { String($0) }
}
}
let protocolSalt = "CryptoKit Playgrounds Putting It Together".data(using: .utf8)!
/// Generates an ephemeral key agreement key and performs key agreement to get the shared secret and derive the symmetric encryption key.
func encrypt(_ data: Data, to theirEncryptionKey: Curve25519.KeyAgreement.PublicKey, signedBy ourSigningKey: Curve25519.Signing.PrivateKey) throws ->
(ephemeralPublicKeyData: Data, ciphertext: Data, signature: Data) {
let ephemeralKey = Curve25519.KeyAgreement.PrivateKey()
let ephemeralPublicKey = ephemeralKey.publicKey.rawRepresentation
let sharedSecret = try ephemeralKey.sharedSecretFromKeyAgreement(with: theirEncryptionKey)
let symmetricKey = sharedSecret.hkdfDerivedSymmetricKey(using: SHA256.self,
salt: protocolSalt,
sharedInfo: ephemeralPublicKey +
theirEncryptionKey.rawRepresentation +
ourSigningKey.publicKey.rawRepresentation,
outputByteCount: 32)
let ciphertext = try ChaChaPoly.seal(data, using: symmetricKey).combined
let signature = try ourSigningKey.signature(for: ciphertext + ephemeralPublicKey + theirEncryptionKey.rawRepresentation)
return (ephemeralPublicKey, ciphertext, signature)
}