-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEncrypter.swift
More file actions
30 lines (21 loc) · 930 Bytes
/
Encrypter.swift
File metadata and controls
30 lines (21 loc) · 930 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import Security
import Foundation
enum EncryptionError: ErrorType {
case EncryptionFailed(code: OSStatus)
case DecryptionFailed(code: OSStatus)
case TextDecodingFailed
}
class Encrypter {
func ecnrypt(message: String, publicKey: SecKey) throws -> NSData {
let blockSize = SecKeyGetBlockSize(publicKey)
let plainTextData = [UInt8](message.utf8)
let plainTextDataLength = Int(plainTextData.count)
var encryptedData = [UInt8](count: Int(blockSize), repeatedValue: 0)
var encryptedDataLength = blockSize
let result = SecKeyEncrypt(publicKey, SecPadding(arrayLiteral: SecPadding.PKCS1), plainTextData, plainTextDataLength, &encryptedData, &encryptedDataLength)
guard result == errSecSuccess else {
throw EncryptionError.EncryptionFailed(code: result)
}
return NSData(bytes: encryptedData, length: encryptedDataLength)
}
}