-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHWAESCryption.swift
84 lines (76 loc) · 3.06 KB
/
HWAESCryption.swift
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
//
// HWAESCryption.swift
// AESTest
//
// Created by hanwe on 2020/07/11.
// Copyright © 2020 hanwe. All rights reserved.
//
import Foundation
import CommonCrypto
enum HW_AES_Type {
case aes128
case aes256
}
class HWAESCryption {
static func aesEncrypt(originalData:Data,iv:Data,key:Data,aesType:HW_AES_Type) -> Data {
switch aesType {
case .aes128:
return aesCrypt(data: originalData,
iv: iv,
key: key,
context: CCOperation(kCCEncrypt),
aesSize: size_t(kCCKeySizeAES128)) ?? Data()
case .aes256:
return aesCrypt(data: originalData,
iv: iv,
key: key,
context: CCOperation(kCCEncrypt),
aesSize: size_t(kCCKeySizeAES256)) ?? Data()
}
}
static func aesDecrypt(encData:Data,iv:Data,key:Data,aesType:HW_AES_Type) -> Data? {
switch aesType {
case .aes128:
return aesCrypt(data: encData,
iv: iv,
key: key,
context: CCOperation(kCCDecrypt),
aesSize: size_t(kCCKeySizeAES128))
case .aes256:
return aesCrypt(data: encData,
iv: iv,
key: key,
context: CCOperation(kCCDecrypt),
aesSize: size_t(kCCKeySizeAES256))
}
}
static private func aesCrypt(data:Data,iv:Data,key:Data,context:CCOperation,aesSize:size_t) -> Data? { //todo deprecated된 함수들 교체 //테스트하기
// CCCryptorStatus ccStatus = kCCSuccess;
var numBytesEncrypted :size_t = 0 // Number of bytes moved to buffer.
let cryptLength = size_t(data.count + kCCBlockSizeAES128) // 이거는 aes 128이든 256이든 고정인가??
var cryptData = Data(count:cryptLength)
// NSMutableData *dataOut = [NSMutableData dataWithLength:dataIn.length + kCCBlockSizeAES128];
let cryptStatus = cryptData.withUnsafeMutableBytes {cryptBytes in
data.withUnsafeBytes {dataBytes in
iv.withUnsafeBytes {ivBytes in
key.withUnsafeBytes {keyBytes in
CCCrypt(CCOperation(context),
CCAlgorithm(kCCAlgorithmAES),
CCOptions(kCCOptionPKCS7Padding),
keyBytes, aesSize,
ivBytes,
dataBytes, data.count,
cryptBytes, cryptLength,
&numBytesEncrypted)
}
}
}
}
if UInt32(cryptStatus) == UInt32(kCCSuccess) {
cryptData.removeSubrange(numBytesEncrypted..<cryptData.count)
} else {
return nil
}
return cryptData
}
}