-
Notifications
You must be signed in to change notification settings - Fork 121
Expand file tree
/
Copy pathSwCrypt.swift
More file actions
2423 lines (2052 loc) · 73.8 KB
/
SwCrypt.swift
File metadata and controls
2423 lines (2052 loc) · 73.8 KB
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import Foundation
open class SwKeyStore {
public enum SecError: OSStatus, Error {
case unimplemented = -4
case param = -50
case allocate = -108
case notAvailable = -25291
case authFailed = -25293
case duplicateItem = -25299
case itemNotFound = -25300
case interactionNotAllowed = -25308
case decode = -26275
case missingEntitlement = -34018
public static var debugLevel = 1
init(_ status: OSStatus, function: String = #function, file: String = #file, line: Int = #line) {
self = SecError(rawValue: status)!
if SecError.debugLevel > 0 {
print("\(file):\(line): [\(function)] \(self._domain): \(self) (\(self.rawValue))")
}
}
init(_ type: SecError, function: String = #function, file: String = #file, line: Int = #line) {
self = type
if SecError.debugLevel > 0 {
print("\(file):\(line): [\(function)] \(self._domain): \(self) (\(self.rawValue))")
}
}
}
public static func upsertKey(_ pemKey: String, keyTag: String,
options: [NSString : AnyObject] = [:]) throws {
let pemKeyAsData = pemKey.data(using: String.Encoding.utf8)!
var parameters: [NSString : AnyObject] = [
kSecClass: kSecClassKey,
kSecAttrKeyType: kSecAttrKeyTypeRSA,
kSecAttrIsPermanent: true as AnyObject,
kSecAttrApplicationTag: keyTag as AnyObject,
kSecValueData: pemKeyAsData as AnyObject
]
options.forEach { k, v in
parameters[k] = v
}
var status = SecItemAdd(parameters as CFDictionary, nil)
if status == errSecDuplicateItem {
try delKey(keyTag)
status = SecItemAdd(parameters as CFDictionary, nil)
}
guard status == errSecSuccess else { throw SecError(status) }
}
public static func getKey(_ keyTag: String) throws -> String {
let parameters: [NSString : AnyObject] = [
kSecClass : kSecClassKey,
kSecAttrKeyType : kSecAttrKeyTypeRSA,
kSecAttrApplicationTag : keyTag as AnyObject,
kSecReturnData : true as AnyObject
]
var data: AnyObject?
let status = SecItemCopyMatching(parameters as CFDictionary, &data)
guard status == errSecSuccess else { throw SecError(status) }
guard let pemKeyAsData = data as? Data else {
throw SecError(.decode)
}
guard let result = String(data: pemKeyAsData, encoding: String.Encoding.utf8) else {
throw SecError(.decode)
}
return result
}
public static func delKey(_ keyTag: String) throws {
let parameters: [NSString : AnyObject] = [
kSecClass : kSecClassKey,
kSecAttrApplicationTag: keyTag as AnyObject
]
let status = SecItemDelete(parameters as CFDictionary)
guard status == errSecSuccess else { throw SecError(status) }
}
}
open class SwKeyConvert {
public enum SwError: Error {
case invalidKey
case badPassphrase
case keyNotEncrypted
public static var debugLevel = 1
init(_ type: SwError, function: String = #function, file: String = #file, line: Int = #line) {
self = type
if SwError.debugLevel > 0 {
print("\(file):\(line): [\(function)] \(self._domain): \(self)")
}
}
}
open class PrivateKey {
public static func pemToPKCS1DER(_ pemKey: String) throws -> Data {
guard let derKey = try? PEM.PrivateKey.toDER(pemKey) else {
throw SwError(.invalidKey)
}
guard let pkcs1DERKey = PKCS8.PrivateKey.stripHeaderIfAny(derKey) else {
throw SwError(.invalidKey)
}
return pkcs1DERKey
}
public static func derToPKCS1PEM(_ derKey: Data) -> String {
return PEM.PrivateKey.toPEM(derKey)
}
public typealias EncMode = PEM.EncryptedPrivateKey.EncMode
public static func encryptPEM(_ pemKey: String, passphrase: String,
mode: EncMode) throws -> String {
do {
let derKey = try PEM.PrivateKey.toDER(pemKey)
return PEM.EncryptedPrivateKey.toPEM(derKey, passphrase: passphrase, mode: mode)
} catch {
throw SwError(.invalidKey)
}
}
public static func decryptPEM(_ pemKey: String, passphrase: String) throws -> String {
do {
let derKey = try PEM.EncryptedPrivateKey.toDER(pemKey, passphrase: passphrase)
return PEM.PrivateKey.toPEM(derKey)
} catch PEM.SwError.badPassphrase {
throw SwError(.badPassphrase)
} catch PEM.SwError.keyNotEncrypted {
throw SwError(.keyNotEncrypted)
} catch {
throw SwError(.invalidKey)
}
}
}
open class PublicKey {
public static func pemToPKCS1DER(_ pemKey: String) throws -> Data {
guard let derKey = try? PEM.PublicKey.toDER(pemKey) else {
throw SwError(.invalidKey)
}
guard let pkcs1DERKey = PKCS8.PublicKey.stripHeaderIfAny(derKey) else {
throw SwError(.invalidKey)
}
return pkcs1DERKey
}
public static func pemToPKCS8DER(_ pemKey: String) throws -> Data {
guard let derKey = try? PEM.PublicKey.toDER(pemKey) else {
throw SwError(.invalidKey)
}
return derKey
}
public static func derToPKCS1PEM(_ derKey: Data) -> String {
return PEM.PublicKey.toPEM(derKey)
}
public static func derToPKCS8PEM(_ derKey: Data) -> String {
let pkcs8Key = PKCS8.PublicKey.addHeader(derKey)
return PEM.PublicKey.toPEM(pkcs8Key)
}
}
}
open class PKCS8 {
open class PrivateKey {
// https://lapo.it/asn1js/
public static func getPKCS1DEROffset(_ derKey: Data) -> Int? {
let bytes = derKey.bytesView
var offset = 0
guard bytes.length > offset else { return nil }
guard bytes[offset] == 0x30 else { return nil }
offset += 1
guard bytes.length > offset else { return nil }
if bytes[offset] > 0x80 {
offset += Int(bytes[offset]) - 0x80
}
offset += 1
guard bytes.length > offset else { return nil }
guard bytes[offset] == 0x02 else { return nil }
offset += 3
// without PKCS8 header
guard bytes.length > offset else { return nil }
if bytes[offset] == 0x02 {
return 0
}
let OID: [UInt8] = [0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00]
guard bytes.length > offset + OID.count else { return nil }
let slice = derKey.bytesViewRange(NSRange(location: offset, length: OID.count))
guard OID.elementsEqual(slice) else { return nil }
offset += OID.count
guard bytes.length > offset else { return nil }
guard bytes[offset] == 0x04 else { return nil }
offset += 1
guard bytes.length > offset else { return nil }
if bytes[offset] > 0x80 {
offset += Int(bytes[offset]) - 0x80
}
offset += 1
guard bytes.length > offset else { return nil }
guard bytes[offset] == 0x30 else { return nil }
return offset
}
public static func stripHeaderIfAny(_ derKey: Data) -> Data? {
guard let offset = getPKCS1DEROffset(derKey) else {
return nil
}
return derKey.subdata(in: offset..<derKey.count)
}
public static func hasCorrectHeader(_ derKey: Data) -> Bool {
return getPKCS1DEROffset(derKey) != nil
}
}
open class PublicKey {
public static func addHeader(_ derKey: Data) -> Data {
var result = Data()
let encodingLength: Int = encodedOctets(derKey.count + 1).count
let OID: [UInt8] = [0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00]
var builder: [UInt8] = []
// ASN.1 SEQUENCE
builder.append(0x30)
// Overall size, made of OID + bitstring encoding + actual key
let size = OID.count + 2 + encodingLength + derKey.count
let encodedSize = encodedOctets(size)
builder.append(contentsOf: encodedSize)
result.append(builder, count: builder.count)
result.append(OID, count: OID.count)
builder.removeAll(keepingCapacity: false)
builder.append(0x03)
builder.append(contentsOf: encodedOctets(derKey.count + 1))
builder.append(0x00)
result.append(builder, count: builder.count)
// Actual key bytes
result.append(derKey)
return result
}
// https://lapo.it/asn1js/
public static func getPKCS1DEROffset(_ derKey: Data) -> Int? {
let bytes = derKey.bytesView
var offset = 0
guard bytes.length > offset else { return nil }
guard bytes[offset] == 0x30 else { return nil }
offset += 1
guard bytes.length > offset else { return nil }
if bytes[offset] > 0x80 {
offset += Int(bytes[offset]) - 0x80
}
offset += 1
// without PKCS8 header
guard bytes.length > offset else { return nil }
if bytes[offset] == 0x02 {
return 0
}
let OID: [UInt8] = [0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00]
guard bytes.length > offset + OID.count else { return nil }
let slice = derKey.bytesViewRange(NSRange(location: offset, length: OID.count))
guard OID.elementsEqual(slice) else { return nil }
offset += OID.count
// Type
guard bytes.length > offset else { return nil }
guard bytes[offset] == 0x03 else { return nil }
offset += 1
guard bytes.length > offset else { return nil }
if bytes[offset] > 0x80 {
offset += Int(bytes[offset]) - 0x80
}
offset += 1
// Contents should be separated by a null from the header
guard bytes.length > offset else { return nil }
guard bytes[offset] == 0x00 else { return nil }
offset += 1
guard bytes.length > offset else { return nil }
return offset
}
public static func stripHeaderIfAny(_ derKey: Data) -> Data? {
guard let offset = getPKCS1DEROffset(derKey) else {
return nil
}
return derKey.subdata(in: offset..<derKey.count)
}
public static func hasCorrectHeader(_ derKey: Data) -> Bool {
return getPKCS1DEROffset(derKey) != nil
}
fileprivate static func encodedOctets(_ int: Int) -> [UInt8] {
// Short form
if int < 128 {
return [UInt8(int)]
}
// Long form
let i = (int / 256) + 1
var len = int
var result: [UInt8] = [UInt8(i + 0x80)]
for _ in 0..<i {
result.insert(UInt8(len & 0xFF), at: 1)
len = len >> 8
}
return result
}
}
}
open class PEM {
public enum SwError: Error {
case parse(String)
case badPassphrase
case keyNotEncrypted
public static var debugLevel = 1
init(_ type: SwError, function: String = #function, file: String = #file, line: Int = #line) {
self = type
if SwError.debugLevel > 0 {
print("\(file):\(line): [\(function)] \(self._domain): \(self)")
}
}
}
open class PrivateKey {
public static func toDER(_ pemKey: String) throws -> Data {
guard let strippedKey = stripHeader(pemKey) else {
throw SwError(.parse("header"))
}
guard let data = PEM.base64Decode(strippedKey) else {
throw SwError(.parse("base64decode"))
}
return data
}
public static func toPEM(_ derKey: Data) -> String {
let base64 = PEM.base64Encode(derKey)
return addRSAHeader(base64)
}
fileprivate static let prefix = "-----BEGIN PRIVATE KEY-----\n"
fileprivate static let suffix = "\n-----END PRIVATE KEY-----"
fileprivate static let rsaPrefix = "-----BEGIN RSA PRIVATE KEY-----\n"
fileprivate static let rsaSuffix = "\n-----END RSA PRIVATE KEY-----"
fileprivate static func addHeader(_ base64: String) -> String {
return prefix + base64 + suffix
}
fileprivate static func addRSAHeader(_ base64: String) -> String {
return rsaPrefix + base64 + rsaSuffix
}
fileprivate static func stripHeader(_ pemKey: String) -> String? {
return PEM.stripHeaderFooter(pemKey, header: prefix, footer: suffix) ??
PEM.stripHeaderFooter(pemKey, header: rsaPrefix, footer: rsaSuffix)
}
}
open class PublicKey {
public static func toDER(_ pemKey: String) throws -> Data {
guard let strippedKey = stripHeader(pemKey) else {
throw SwError(.parse("header"))
}
guard let data = PEM.base64Decode(strippedKey) else {
throw SwError(.parse("base64decode"))
}
return data
}
public static func toPEM(_ derKey: Data) -> String {
let base64 = PEM.base64Encode(derKey)
return addHeader(base64)
}
fileprivate static let pemPrefix = "-----BEGIN PUBLIC KEY-----\n"
fileprivate static let pemSuffix = "\n-----END PUBLIC KEY-----"
fileprivate static func addHeader(_ base64: String) -> String {
return pemPrefix + base64 + pemSuffix
}
fileprivate static func stripHeader(_ pemKey: String) -> String? {
return PEM.stripHeaderFooter(pemKey, header: pemPrefix, footer: pemSuffix)
}
}
// OpenSSL PKCS#1 compatible encrypted private key
open class EncryptedPrivateKey {
public enum EncMode {
case aes128CBC, aes256CBC
}
public static func toDER(_ pemKey: String, passphrase: String) throws -> Data {
guard let strippedKey = PrivateKey.stripHeader(pemKey) else {
throw SwError(.parse("header"))
}
guard let mode = getEncMode(strippedKey) else {
throw SwError(.keyNotEncrypted)
}
guard let iv = getIV(strippedKey) else {
throw SwError(.parse("iv"))
}
let aesKey = getAESKey(mode, passphrase: passphrase, iv: iv)
let base64Data = String(strippedKey[strippedKey.index(strippedKey.startIndex, offsetBy: aesHeaderLength)...])
guard let data = PEM.base64Decode(base64Data) else {
throw SwError(.parse("base64decode"))
}
guard let decrypted = try? decryptKey(data, key: aesKey, iv: iv) else {
throw SwError(.badPassphrase)
}
guard PKCS8.PrivateKey.hasCorrectHeader(decrypted) else {
throw SwError(.badPassphrase)
}
return decrypted
}
public static func toPEM(_ derKey: Data, passphrase: String, mode: EncMode) -> String {
let iv = CC.generateRandom(16)
let aesKey = getAESKey(mode, passphrase: passphrase, iv: iv)
let encrypted = encryptKey(derKey, key: aesKey, iv: iv)
let encryptedDERKey = addEncryptHeader(encrypted, iv: iv, mode: mode)
return PrivateKey.addRSAHeader(encryptedDERKey)
}
fileprivate static let aes128CBCInfo = "Proc-Type: 4,ENCRYPTED\nDEK-Info: AES-128-CBC,"
fileprivate static let aes256CBCInfo = "Proc-Type: 4,ENCRYPTED\nDEK-Info: AES-256-CBC,"
fileprivate static let aesInfoLength = aes128CBCInfo.count
fileprivate static let aesIVInHexLength = 32
fileprivate static let aesHeaderLength = aesInfoLength + aesIVInHexLength
fileprivate static func addEncryptHeader(_ key: Data, iv: Data, mode: EncMode) -> String {
return getHeader(mode) + iv.hexadecimalString() + "\n\n" + PEM.base64Encode(key)
}
fileprivate static func getHeader(_ mode: EncMode) -> String {
switch mode {
case .aes128CBC: return aes128CBCInfo
case .aes256CBC: return aes256CBCInfo
}
}
fileprivate static func getEncMode(_ strippedKey: String) -> EncMode? {
if strippedKey.hasPrefix(aes128CBCInfo) {
return .aes128CBC
}
if strippedKey.hasPrefix(aes256CBCInfo) {
return .aes256CBC
}
return nil
}
fileprivate static func getIV(_ strippedKey: String) -> Data? {
let ivInHex = String(strippedKey[strippedKey.index(strippedKey.startIndex, offsetBy: aesInfoLength) ..< strippedKey.index(strippedKey.startIndex, offsetBy: aesHeaderLength)])
return ivInHex.dataFromHexadecimalString()
}
fileprivate static func getAESKey(_ mode: EncMode, passphrase: String, iv: Data) -> Data {
switch mode {
case .aes128CBC: return getAES128Key(passphrase, iv: iv)
case .aes256CBC: return getAES256Key(passphrase, iv: iv)
}
}
fileprivate static func getAES128Key(_ passphrase: String, iv: Data) -> Data {
// 128bit_Key = MD5(Passphrase + Salt)
let pass = passphrase.data(using: String.Encoding.utf8)!
let salt = iv.subdata(in: 0..<8)
var key = pass
key.append(salt)
return CC.digest(key, alg: .md5)
}
fileprivate static func getAES256Key(_ passphrase: String, iv: Data) -> Data {
// 128bit_Key = MD5(Passphrase + Salt)
// 256bit_Key = 128bit_Key + MD5(128bit_Key + Passphrase + Salt)
let pass = passphrase.data(using: String.Encoding.utf8)!
let salt = iv.subdata(in: 0 ..< 8)
var first = pass
first.append(salt)
let aes128Key = CC.digest(first, alg: .md5)
var sec = aes128Key
sec.append(pass)
sec.append(salt)
var aes256Key = aes128Key
aes256Key.append(CC.digest(sec, alg: .md5))
return aes256Key
}
fileprivate static func encryptKey(_ data: Data, key: Data, iv: Data) -> Data {
return try! CC.crypt(
.encrypt, blockMode: .cbc, algorithm: .aes, padding: .pkcs7Padding,
data: data, key: key, iv: iv)
}
fileprivate static func decryptKey(_ data: Data, key: Data, iv: Data) throws -> Data {
return try CC.crypt(
.decrypt, blockMode: .cbc, algorithm: .aes, padding: .pkcs7Padding,
data: data, key: key, iv: iv)
}
}
fileprivate static func stripHeaderFooter(_ data: String, header: String, footer: String) -> String? {
guard data.hasPrefix(header) else {
return nil
}
guard let r = data.range(of: footer) else {
return nil
}
return String(data[header.endIndex ..< r.lowerBound])
}
fileprivate static func base64Decode(_ base64Data: String) -> Data? {
return Data(base64Encoded: base64Data, options: [.ignoreUnknownCharacters])
}
fileprivate static func base64Encode(_ key: Data) -> String {
return key.base64EncodedString(
options: [.lineLength64Characters, .endLineWithLineFeed])
}
}
open class CC {
public typealias CCCryptorStatus = Int32
public enum CCError: CCCryptorStatus, Error {
case paramError = -4300
case bufferTooSmall = -4301
case memoryFailure = -4302
case alignmentError = -4303
case decodeError = -4304
case unimplemented = -4305
case overflow = -4306
case rngFailure = -4307
case unspecifiedError = -4308
case callSequenceError = -4309
case keySizeError = -4310
case invalidKey = -4311
public static var debugLevel = 1
init(_ status: CCCryptorStatus, function: String = #function,
file: String = #file, line: Int = #line) {
self = CCError(rawValue: status)!
if CCError.debugLevel > 0 {
print("\(file):\(line): [\(function)] \(self._domain): \(self) (\(self.rawValue))")
}
}
init(_ type: CCError, function: String = #function, file: String = #file, line: Int = #line) {
self = type
if CCError.debugLevel > 0 {
print("\(file):\(line): [\(function)] \(self._domain): \(self) (\(self.rawValue))")
}
}
}
public static func generateRandom(_ size: Int) -> Data {
var data = Data(count: size)
data.withUnsafeMutableBytes { dataBytes -> Void in
_ = CCRandomGenerateBytes!(dataBytes.baseAddress!, size)
return
}
return data
}
public typealias CCDigestAlgorithm = UInt32
public enum DigestAlgorithm: CCDigestAlgorithm {
case none = 0
case md5 = 3
case rmd128 = 4, rmd160 = 5, rmd256 = 6, rmd320 = 7
case sha1 = 8
case sha224 = 9, sha256 = 10, sha384 = 11, sha512 = 12
var length: Int {
return CCDigestGetOutputSize!(self.rawValue)
}
}
public static func digest(_ data: Data, alg: DigestAlgorithm) -> Data {
var output = Data(count: alg.length)
withUnsafePointers(data, &output, { dataBytes, outputBytes in
_ = CCDigest!(alg.rawValue,
dataBytes,
data.count,
outputBytes)
})
return output
}
public typealias CCHmacAlgorithm = UInt32
public enum HMACAlg: CCHmacAlgorithm {
case sha1, md5, sha256, sha384, sha512, sha224
var digestLength: Int {
switch self {
case .sha1: return 20
case .md5: return 16
case .sha256: return 32
case .sha384: return 48
case .sha512: return 64
case .sha224: return 28
}
}
}
public static func HMAC(_ data: Data, alg: HMACAlg, key: Data) -> Data {
var buffer = Data(count: alg.digestLength)
withUnsafePointers(key, data, &buffer, { keyBytes, dataBytes, bufferBytes in
CCHmac!(alg.rawValue,
keyBytes, key.count,
dataBytes, data.count,
bufferBytes)
})
return buffer
}
public typealias CCOperation = UInt32
public enum OpMode: CCOperation {
case encrypt = 0, decrypt
}
public typealias CCMode = UInt32
public enum BlockMode: CCMode {
case ecb = 1, cbc, cfb, ctr, f8, lrw, ofb, xts, rc4, cfb8
var needIV: Bool {
switch self {
case .cbc, .cfb, .ctr, .ofb, .cfb8: return true
default: return false
}
}
}
public enum AuthBlockMode: CCMode {
case gcm = 11, ccm
}
public typealias CCAlgorithm = UInt32
public enum Algorithm: CCAlgorithm {
case aes = 0, des, threeDES, cast, rc4, rc2, blowfish
var blockSize: Int? {
switch self {
case .aes: return 16
case .des: return 8
case .threeDES: return 8
case .cast: return 8
case .rc2: return 8
case .blowfish: return 8
default: return nil
}
}
}
public typealias CCPadding = UInt32
public enum Padding: CCPadding {
case noPadding = 0, pkcs7Padding
}
public static func crypt(_ opMode: OpMode, blockMode: BlockMode,
algorithm: Algorithm, padding: Padding,
data: Data, key: Data, iv: Data) throws -> Data {
if blockMode.needIV {
guard iv.count == algorithm.blockSize else { throw CCError(.paramError) }
}
var cryptor: CCCryptorRef? = nil
var status = withUnsafePointers(iv, key, { ivBytes, keyBytes in
return CCCryptorCreateWithMode!(
opMode.rawValue, blockMode.rawValue,
algorithm.rawValue, padding.rawValue,
ivBytes, keyBytes, key.count,
nil, 0, 0,
CCModeOptions(), &cryptor)
})
guard status == noErr else { throw CCError(status) }
defer { _ = CCCryptorRelease!(cryptor!) }
let needed = CCCryptorGetOutputLength!(cryptor!, data.count, true)
var result = Data(count: needed)
let rescount = result.count
var updateLen: size_t = 0
status = withUnsafePointers(data, &result, { dataBytes, resultBytes in
return CCCryptorUpdate!(
cryptor!,
dataBytes, data.count,
resultBytes, rescount,
&updateLen)
})
guard status == noErr else { throw CCError(status) }
var finalLen: size_t = 0
status = result.withUnsafeMutableBytes { resultBytes -> OSStatus in
return CCCryptorFinal!(
cryptor!,
resultBytes.baseAddress! + updateLen,
rescount - updateLen,
&finalLen)
}
guard status == noErr else { throw CCError(status) }
result.count = updateLen + finalLen
return result
}
// The same behaviour as in the CCM pdf
// http://csrc.nist.gov/publications/nistpubs/800-38C/SP800-38C_updated-July20_2007.pdf
public static func cryptAuth(_ opMode: OpMode, blockMode: AuthBlockMode, algorithm: Algorithm,
data: Data, aData: Data,
key: Data, iv: Data, tagLength: Int) throws -> Data {
let cryptFun = blockMode == .gcm ? GCM.crypt : CCM.crypt
if opMode == .encrypt {
let (cipher, tag) = try cryptFun(opMode, algorithm, data,
key, iv, aData, tagLength)
var result = cipher
result.append(tag)
return result
} else {
let cipher = data.subdata(in: 0..<(data.count - tagLength))
let tag = data.subdata(
in: (data.count - tagLength)..<data.count)
let (plain, vTag) = try cryptFun(opMode, algorithm, cipher,
key, iv, aData, tagLength)
guard tag == vTag else {
throw CCError(.decodeError)
}
return plain
}
}
public static func digestAvailable() -> Bool {
return CCDigest != nil &&
CCDigestGetOutputSize != nil
}
public static func randomAvailable() -> Bool {
return CCRandomGenerateBytes != nil
}
public static func hmacAvailable() -> Bool {
return CCHmac != nil
}
public static func cryptorAvailable() -> Bool {
return CCCryptorCreateWithMode != nil &&
CCCryptorGetOutputLength != nil &&
CCCryptorUpdate != nil &&
CCCryptorFinal != nil &&
CCCryptorRelease != nil
}
public static func available() -> Bool {
return digestAvailable() &&
randomAvailable() &&
hmacAvailable() &&
cryptorAvailable() &&
KeyDerivation.available() &&
KeyWrap.available() &&
RSA.available() &&
DH.available() &&
EC.available() &&
CRC.available() &&
CMAC.available() &&
GCM.available() &&
CCM.available()
}
fileprivate typealias CCCryptorRef = UnsafeRawPointer
fileprivate typealias CCRNGStatus = CCCryptorStatus
fileprivate typealias CC_LONG = UInt32
fileprivate typealias CCModeOptions = UInt32
fileprivate typealias CCRandomGenerateBytesT = @convention(c) (
_ bytes: UnsafeMutableRawPointer,
_ count: size_t) -> CCRNGStatus
fileprivate typealias CCDigestGetOutputSizeT = @convention(c) (
_ algorithm: CCDigestAlgorithm) -> size_t
fileprivate typealias CCDigestT = @convention(c) (
_ algorithm: CCDigestAlgorithm,
_ data: UnsafeRawPointer,
_ dataLen: size_t,
_ output: UnsafeMutableRawPointer) -> CInt
fileprivate typealias CCHmacT = @convention(c) (
_ algorithm: CCHmacAlgorithm,
_ key: UnsafeRawPointer,
_ keyLength: Int,
_ data: UnsafeRawPointer,
_ dataLength: Int,
_ macOut: UnsafeMutableRawPointer) -> Void
fileprivate typealias CCCryptorCreateWithModeT = @convention(c)(
_ op: CCOperation,
_ mode: CCMode,
_ alg: CCAlgorithm,
_ padding: CCPadding,
_ iv: UnsafeRawPointer?,
_ key: UnsafeRawPointer, _ keyLength: Int,
_ tweak: UnsafeRawPointer?, _ tweakLength: Int,
_ numRounds: Int32, _ options: CCModeOptions,
_ cryptorRef: UnsafeMutablePointer<CCCryptorRef?>) -> CCCryptorStatus
fileprivate typealias CCCryptorGetOutputLengthT = @convention(c)(
_ cryptorRef: CCCryptorRef,
_ inputLength: size_t,
_ final: Bool) -> size_t
fileprivate typealias CCCryptorUpdateT = @convention(c)(
_ cryptorRef: CCCryptorRef,
_ dataIn: UnsafeRawPointer,
_ dataInLength: Int,
_ dataOut: UnsafeMutableRawPointer,
_ dataOutAvailable: Int,
_ dataOutMoved: UnsafeMutablePointer<Int>) -> CCCryptorStatus
fileprivate typealias CCCryptorFinalT = @convention(c)(
_ cryptorRef: CCCryptorRef,
_ dataOut: UnsafeMutableRawPointer,
_ dataOutAvailable: Int,
_ dataOutMoved: UnsafeMutablePointer<Int>) -> CCCryptorStatus
fileprivate typealias CCCryptorReleaseT = @convention(c)
(_ cryptorRef: CCCryptorRef) -> CCCryptorStatus
fileprivate static let dl = dlopen("/usr/lib/system/libcommonCrypto.dylib", RTLD_NOW)
fileprivate static let CCRandomGenerateBytes: CCRandomGenerateBytesT? =
getFunc(dl!, f: "CCRandomGenerateBytes")
fileprivate static let CCDigestGetOutputSize: CCDigestGetOutputSizeT? =
getFunc(dl!, f: "CCDigestGetOutputSize")
fileprivate static let CCDigest: CCDigestT? = getFunc(dl!, f: "CCDigest")
fileprivate static let CCHmac: CCHmacT? = getFunc(dl!, f: "CCHmac")
fileprivate static let CCCryptorCreateWithMode: CCCryptorCreateWithModeT? =
getFunc(dl!, f: "CCCryptorCreateWithMode")
fileprivate static let CCCryptorGetOutputLength: CCCryptorGetOutputLengthT? =
getFunc(dl!, f: "CCCryptorGetOutputLength")
fileprivate static let CCCryptorUpdate: CCCryptorUpdateT? =
getFunc(dl!, f: "CCCryptorUpdate")
fileprivate static let CCCryptorFinal: CCCryptorFinalT? =
getFunc(dl!, f: "CCCryptorFinal")
fileprivate static let CCCryptorRelease: CCCryptorReleaseT? =
getFunc(dl!, f: "CCCryptorRelease")
open class GCM {
public static func crypt(_ opMode: OpMode, algorithm: Algorithm, data: Data,
key: Data, iv: Data,
aData: Data, tagLength: Int) throws -> (Data, Data) {
var result = Data(count: data.count)
var tagLength_ = tagLength
var tag = Data(count: tagLength)
let status = withUnsafePointers(key, iv, aData, data, &result, &tag, {
keyBytes, ivBytes, aDataBytes, dataBytes, resultBytes, tagBytes in
return CCCryptorGCM!(opMode.rawValue, algorithm.rawValue,
keyBytes, key.count, ivBytes, iv.count,
aDataBytes, aData.count,
dataBytes, data.count,
resultBytes, tagBytes, &tagLength_)
})
guard status == noErr else { throw CCError(status) }
tag.count = tagLength_
return (result, tag)
}
public static func available() -> Bool {
if CCCryptorGCM != nil {
return true
}
return false
}
fileprivate typealias CCCryptorGCMT = @convention(c) (_ op: CCOperation, _ alg: CCAlgorithm,
_ key: UnsafeRawPointer, _ keyLength: Int,
_ iv: UnsafeRawPointer, _ ivLen: Int,
_ aData: UnsafeRawPointer, _ aDataLen: Int,
_ dataIn: UnsafeRawPointer, _ dataInLength: Int,
_ dataOut: UnsafeMutableRawPointer,
_ tag: UnsafeRawPointer, _ tagLength: UnsafeMutablePointer<Int>) -> CCCryptorStatus
fileprivate static let CCCryptorGCM: CCCryptorGCMT? = getFunc(dl!, f: "CCCryptorGCM")
}
open class CCM {
public static func crypt(_ opMode: OpMode, algorithm: Algorithm, data: Data,
key: Data, iv: Data,
aData: Data, tagLength: Int) throws -> (Data, Data) {
var cryptor: CCCryptorRef? = nil
var status = key.withUnsafeBytes { keyBytes -> OSStatus in
CCCryptorCreateWithMode!(
opMode.rawValue, AuthBlockMode.ccm.rawValue,
algorithm.rawValue, Padding.noPadding.rawValue,
nil, keyBytes.baseAddress!, key.count, nil, 0,
0, CCModeOptions(), &cryptor)
}
guard status == noErr else { throw CCError(status) }
defer { _ = CCCryptorRelease!(cryptor!) }
status = CCCryptorAddParameter!(cryptor!,
Parameter.dataSize.rawValue, nil, data.count)
guard status == noErr else { throw CCError(status) }
status = CCCryptorAddParameter!(cryptor!, Parameter.macSize.rawValue, nil, tagLength)
guard status == noErr else { throw CCError(status) }
status = iv.withUnsafeBytes { ivBytes -> OSStatus in
CCCryptorAddParameter!(cryptor!, Parameter.iv.rawValue, ivBytes.baseAddress!, iv.count)
}
guard status == noErr else { throw CCError(status) }
status = aData.withUnsafeBytes { aDataBytes -> OSStatus in
CCCryptorAddParameter!(cryptor!, Parameter.authData.rawValue, aDataBytes.baseAddress!, aData.count)
}
guard status == noErr else { throw CCError(status) }
var result = Data(count: data.count)
let rescount = result.count
var updateLen: size_t = 0
status = withUnsafePointers(data, &result, { dataBytes, resultBytes in
return CCCryptorUpdate!(
cryptor!, dataBytes, data.count,
resultBytes, rescount,
&updateLen)
})
guard status == noErr else { throw CCError(status) }
var finalLen: size_t = 0
status = result.withUnsafeMutableBytes { resultBytes -> OSStatus in
CCCryptorFinal!(cryptor!, resultBytes.baseAddress! + updateLen,
rescount - updateLen,
&finalLen)
}
guard status == noErr else { throw CCError(status) }