Envelope
Swift 中的 OpenSSL 兼容文件加密
Envelope 是一个混合加密系统,可以高效且安全地加密文件,支持大多数对称和公钥加密算法。Envelope 默认使用 AES256-CBC
和 RSA-2048
,并支持外部创建的(即 OpenSSL)公钥。
Envelope 被用于TunnelBear,作为不可达服务器时的后备方法,通过电子邮件发送应用程序日志。
混合加密
公钥加密(例如 RSA)通常速度较慢、效率低下,且存在明文字大小限制。对称加密(例如 AES)需要安全密钥交换,这可能并不总是可行。混合加密系统使用这两种密钥类型同时工作,高效加密明文,而不需要安全的密钥交换。
Envelope 解除了开发人员导入大型的加密框架(如 CryptoSwift 和 SwiftyRSA)的需求,仅仅是为了使用单一对称/公钥密钥对加密文件。
特点
- 无第三方依赖
- 支持通过导入
X.509 证书
使用外部创建的公钥 - 支持多种 公钥加密算法
- 实现了具有自动盐 + IV 随机化和密钥生成的
AES256-CBC
,轻量级实现 - 支持自定义对称加密算法实现
- 易于集成到现有项目中
- 基于苹果公司可靠
CommonCrypto
库推导出的加密逻辑
安装
可以使用CocoaPods、Carthage或直接将框架嵌入到最新的GitHub release中的应用中进行安装。
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!
}
自定义对称加密
信封支持通过 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)