信封
Swift中的OpenSSL兼容文件加密
信封是一个混合加密系统,可以高效且安全地加密文件,支持大多数对称和公钥加密。信封默认使用AES256-CBC
和RSA-2048
,并支持外部创建(即OpenSSL)的公钥。
信封在TunnelBear中被用作当服务器不可用时发送应用程序日志的回退方法。
混合加密
公钥密码(如RSA)通常速度慢,效率低,并且有明文大小限制。对称密码(如AES)需要安全密钥交换,这可能并不总是可能的。混合加密系统同时使用这两种类型的密码,从而有效地加密明文,而无需安全密钥交换。
信封消除了开发人员只需导入大型加密框架(如CryptoSwift 和 SwiftyRSA)来使用单一对称/公钥密码对加密文件的需求。
功能
- 无第三方依赖
- 支持通过导入
X.509证书
使用外部创建的公钥 - 支持许多公钥密码
AES256-CBC
的轻量级实现,具有自动盐值+ IV随机化和密钥生成- 支持自定义对称密码实现
- 易于集成到现有项目中
- 加密逻辑源自苹果可靠的
CommonCrypto
库
安装
可以使用CocoaPods、Carthage或从最新版 GitHub发行版 直接嵌入框架进行安装。
CocoaPods
pod 'Envelope'
Carthage
github "george-lim/envelope"
安装后,您需要在您的应用程序中导入一个 X.509证书
。
要创建新的RSA-2048
公钥加证书,请在终端执行以下操作
openssl req -newkey rsa:2048 -nodes -keyout privateKey.pem -x509 -out certificate.pem
openssl x509 -outform der -in certificate.pem -out certificate.der
然后将其中的 certificate.der
拖放到您的应用程序中,确保勾选 如果需要则复制项目
并选择 创建组合
。
用法
信封加密
// Uses `password` and a random 32-character salt for key generation, and random IV
let defaultEnvelope = try Envelope(derNamed: "certificate", password: "some AES password")
// Support for custom bundle where certificate is stored, public-key algorithm, random salt length, and AES keygen runtime (in ms)
let customEnvelope = try Envelope(derNamed: "certificate",
in: Bundle.main,
algorithm: .rsaEncryptionPKCS1,
password: "some AES password",
randomSaltLength: 8,
runtime: 1000)
// Support for `String` or `Data` plaintext
let ciphertext = try defaultEnvelope.encrypt("Hello world!")
// Send ciphertext.key and ciphertext.data to server for decryption
print(ciphertext.key)
print(ciphertext.data)
信封解密
假设您有一个包含 privateKey.pem
、ciphertext.key
和 ciphertext.data
文件的文件夹,在终端中执行以下操作
set -- $(openssl rsautl -decrypt -inkey privateKey.pem -in ciphertext.key)
openssl aes-256-cbc -K $1 -iv $2 -d -in ciphertext.data out plaintext
AES256-CBC 加密操作
由于信封包含 AES256-CBC
实现,它可以用于对 String
或 Data
明文进行加密操作。
let aes = try AES256CBC(password: "some AES password")
let ciphertext = try aes.encrypt("Hello world!")
if let plaintext: String = try aes.decrypt(ciphertext) {
print(plaintext) // Hello world!
}
自定义对称加密
Envelope 通过 SymmetricCipher
协议支持自定义对称加密。
示例
class CustomCipher: SymmetricCipher {
var sharedSecret: CFData {
return ...
}
func encrypt(_ plaintext: Data) throws -> Data {
...
}
func decrypt(_ ciphertext: Data) throws -> Data {
...
}
}
let symmetricCipher = CustomCipher()
let envelope = try Envelope(derNamed: "certificate", symmetricCipher: symmetricCipher)
let ciphertext = try envelope.encrypt("Hello world!")
许可证
此项目受 MIT 许可证版权保护。完整许可证可在以下位置找到:[此处](https://github.com/george-lim/envelope/blob/master/LICENSE)