Skip to content

Instantly share code, notes, and snippets.

@mehmeteminkartal
Created January 27, 2021 19:37
Show Gist options
  • Save mehmeteminkartal/e2d1ee56526dc032b7257aef80c40d16 to your computer and use it in GitHub Desktop.
Save mehmeteminkartal/e2d1ee56526dc032b7257aef80c40d16 to your computer and use it in GitHub Desktop.
import Foundation
import Crypto // https://github.com/apple/swift-crypto
extension Data {
struct HexEncodingOptions: OptionSet {
let rawValue: Int
static let upperCase = HexEncodingOptions(rawValue: 1 << 0)
}
func hexEncodedString(options: HexEncodingOptions = []) -> String {
let format = options.contains(.upperCase) ? "%02hhX" : "%02hhx"
return map { String(format: format, $0) }.joined()
}
}
// Data dump methods
let bobPrivateKey = Curve25519.KeyAgreement.PrivateKey()
let alicePrivateKey = Curve25519.KeyAgreement.PrivateKey()
let bobPublicKey = bobPrivateKey.publicKey
let alicePublicKey = alicePrivateKey.publicKey
// Bob sends his Public key to Alice
print(bobPublicKey.rawRepresentation.base64EncodedString())
do {
// Each party creats a shared secret from each others public keys
let shared_secret_bob = try bobPrivateKey.sharedSecretFromKeyAgreement(with: alicePublicKey)
let shared_secret_alice = try alicePrivateKey.sharedSecretFromKeyAgreement(with: bobPublicKey)
// Bob creates shared key
let bobs_key = shared_secret_bob.x963DerivedSymmetricKey(using: Crypto.SHA512.self , sharedInfo: bobPublicKey.rawRepresentation, outputByteCount: 16)
let message = "Testing123..."
// and encripts some data with it
let sealedMessage = try AES.GCM.seal(message.data(using: .utf8)!, using: bobs_key)
print(sealedMessage.ciphertext.hexEncodedString(options: [.upperCase]))
// Alice creates the same shared key
let alice_key = shared_secret_alice.x963DerivedSymmetricKey(using: Crypto.SHA512.self , sharedInfo: bobPublicKey.rawRepresentation, outputByteCount: 16)
// and decripts encrypted message with it
let unsealed_message = try AES.GCM.open(sealedMessage, using: alice_key);
let string = String.init(data: unsealed_message, encoding: .utf8) ?? "Error"
// Get the decrypred message
print(string)
} catch {
print(error.localizedDescription)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment