Added DiffieHellman class

pull/38/head
Mikunj 6 years ago
parent 31a6ef4769
commit c5b9d8c7e2

@ -1 +1 @@
Subproject commit 40bc969de75f70d546256db090dec25fe4661120
Subproject commit d2cc7e97d653ab30ffadedd8034f6d8d27c27775

@ -6,14 +6,10 @@
<dict>
<key>CarthageVersion</key>
<string>0.33.0</string>
<key>DateTime</key>
<string>Thu Jul 18 04:53:39 UTC 2019</string>
<key>OSXVersion</key>
<string>10.14.5</string>
<string>10.14.6</string>
<key>WebRTCCommit</key>
<string>1445d719bf05280270e9f77576f80f973fd847f8 M73</string>
<key>XCodeVersion</key>
<string>1000.1020</string>
</dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>

@ -0,0 +1,43 @@
import CryptoSwift
import Curve25519Kit
public enum DiffieHellman {
// The length of the iv
public static let ivLength: Int32 = 16;
public static func encrypt(plainText: Data, symmetricKey: Data) throws -> Data {
let iv = Randomness.generateRandomBytes(ivLength)!
let ivBytes = [UInt8](iv)
let symmetricKeyBytes = [UInt8](symmetricKey)
let messageBytes = [UInt8](plainText)
let blockMode = CBC(iv: ivBytes)
let aes = try AES(key: symmetricKeyBytes, blockMode: blockMode)
let cipherText = try aes.encrypt(messageBytes)
let ivAndCipher = ivBytes + cipherText
return Data(bytes: ivAndCipher, count: ivAndCipher.count)
}
public static func encrypt(plainText: Data, publicKey: Data, privateKey: Data) throws -> Data {
let symmetricKey = try Curve25519.generateSharedSecret(fromPublicKey: publicKey, privateKey: privateKey)
return try encrypt(plainText: plainText, symmetricKey: symmetricKey)
}
public static func decrypt(cipherText: Data, symmetricKey: Data) throws -> Data {
let symmetricKeyBytes = [UInt8](symmetricKey)
let ivBytes = [UInt8](cipherText[..<ivLength])
let cipherBytes = [UInt8](cipherText[ivLength...])
let blockMode = CBC(iv: ivBytes)
let aes = try AES(key: symmetricKeyBytes, blockMode: blockMode)
let decrypted = try aes.decrypt(cipherBytes)
return Data(bytes: decrypted, count: decrypted.count)
}
public static func decrypt(cipherText: Data, publicKey: Data, privateKey: Data) throws -> Data {
let symmetricKey = try Curve25519.generateSharedSecret(fromPublicKey: publicKey, privateKey: privateKey)
return try decrypt(cipherText: cipherText, symmetricKey: symmetricKey)
}
}
Loading…
Cancel
Save