- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
尝试在 Swift 5
中编写我自己的加密/解密函数,基于大量其他类似的问题——结果惨遭失败。
我正在使用 CommonCrypto
+ CCCrypt
来加密/解密(AES,256 key ,随机 iv)。
我更喜欢 NSData.bytes
而不是 withUnsafeBytes
(在 Swift 5
中只是 too confusing)。
我的 encrypt
函数是这样的:
func encrypt(_ string: String) throws -> Data {
guard let dataToEncrypt: Data = string.data(using: .utf8) else {
throw AESError.stringToDataFailed
}
// Seems like the easiest way to avoid the `withUnsafeBytes` mess is to use NSData.bytes.
let dataToEncryptNSData = NSData(data: dataToEncrypt)
let bufferSize: Int = ivSize + dataToEncryptNSData.length + kCCBlockSizeAES128
let buffer = UnsafeMutablePointer<NSData>.allocate(capacity: bufferSize)
defer { buffer.deallocate() }
let status: Int32 = SecRandomCopyBytes(
kSecRandomDefault,
kCCBlockSizeAES128,
buffer
)
guard status == 0 else {
throw AESError.generateRandomIVFailed
}
var numberBytesEncrypted: Int = 0
let cryptStatus: CCCryptorStatus = CCCrypt( // Stateless, one-shot encrypt operation
CCOperation(kCCEncrypt), // op: CCOperation
CCAlgorithm(kCCAlgorithmAES), // alg: CCAlgorithm
options, // options: CCOptions
key.bytes, // key: the "password"
key.length, // keyLength: the "password" size
buffer, // iv: Initialization Vector
dataToEncryptNSData.bytes, // dataIn: Data to encrypt bytes
dataToEncryptNSData.length, // dataInLength: Data to encrypt size
buffer + kCCBlockSizeAES128, // dataOut: encrypted Data buffer
bufferSize, // dataOutAvailable: encrypted Data buffer size
&numberBytesEncrypted // dataOutMoved: the number of bytes written
)
guard cryptStatus == CCCryptorStatus(kCCSuccess) else {
throw AESError.encryptDataFailed
}
return Data(bytes: buffer, count: numberBytesEncrypted + ivSize)
}
解密
函数:
func decrypt(_ data: Data) throws -> String {
// Seems like the easiest way to avoid the `withUnsafeBytes` mess is to use NSData.bytes.
let dataToDecryptNSData = NSData(data: data)
let bufferSize: Int = dataToDecryptNSData.length - ivSize
let buffer = UnsafeMutablePointer<NSData>.allocate(capacity: bufferSize)
defer { buffer.deallocate() }
var numberBytesDecrypted: Int = 0
let cryptStatus: CCCryptorStatus = CCCrypt( // Stateless, one-shot encrypt operation
CCOperation(kCCDecrypt), // op: CCOperation
CCAlgorithm(kCCAlgorithmAES128), // alg: CCAlgorithm
options, // options: CCOptions
key.bytes, // key: the "password"
key.length, // keyLength: the "password" size
dataToDecryptNSData.bytes, // iv: Initialization Vector
dataToDecryptNSData.bytes + kCCBlockSizeAES128, // dataIn: Data to decrypt bytes
bufferSize, // dataInLength: Data to decrypt size
buffer, // dataOut: decrypted Data buffer
bufferSize, // dataOutAvailable: decrypted Data buffer size
&numberBytesDecrypted // dataOutMoved: the number of bytes written
)
guard cryptStatus == CCCryptorStatus(kCCSuccess) else {
throw AESError.decryptDataFailed
}
let decryptedData = Data(bytes: buffer, count: numberBytesDecrypted)
guard let decryptedString = String(data: decryptedData, encoding: .utf8) else {
throw AESError.dataToStringFailed
}
return decryptedString
}
这些是基于 this awesome answer来自用户“@zaph”。
虽然 encrypt
似乎可以正常工作,但 decrypt
却失败了。
这一行具体:
guard let decryptedString = String(data: decryptedData, encoding: .utf8) else {
throw AESError.dataToStringFailed
}
所以我当然错过了一些东西,但我无法弄清楚它是什么。可以吗?
这里是包含完整代码的 pastebin,您可以将其复制/粘贴到 Playground 中并点击播放。 Swift 5
是必需的:https://pastebin.com/raw/h6gacaHX
Update
I'm now following @OOper's suggested approach. The final code can be seen here:
https://github.com/backslash-f/aescryptable
最佳答案
事实上,在 Swift 5 中使用 Data.withUnsafeBytes
有点乱,虽然 NSData.bytes
不是最简单的方法,因为使用它有时看似有效,但有时无效。
如果您想使用 Data
在 Swift 中编写始终有效的代码,则需要习惯使用 Data.withUnsafeBytes
。
struct AES {
private let key: Data //<- Use `Data` instead of `NSData`
private let ivSize: Int = kCCBlockSizeAES128
private let options: CCOptions = CCOptions(kCCOptionPKCS7Padding)
init(keyString: String) throws {
guard keyString.count == kCCKeySizeAES256 else {
throw AESError.invalidKeySize
}
guard let keyData: Data = keyString.data(using: .utf8) else {
throw AESError.stringToDataFailed
}
self.key = keyData
}
}
extension AES: Cryptable {
func encrypt(_ string: String) throws -> Data {
guard let dataToEncrypt: Data = string.data(using: .utf8) else {
throw AESError.stringToDataFailed
}
let bufferSize: Int = ivSize + dataToEncrypt.count + kCCBlockSizeAES128
var buffer = Data(count: bufferSize)
let status: Int32 = buffer.withUnsafeMutableBytes {bytes in
SecRandomCopyBytes(
kSecRandomDefault,
kCCBlockSizeAES128,
bytes.baseAddress!
)
}
guard status == 0 else {
throw AESError.generateRandomIVFailed
}
var numberBytesEncrypted: Int = 0
let cryptStatus: CCCryptorStatus = key.withUnsafeBytes {keyBytes in
dataToEncrypt.withUnsafeBytes {dataBytes in
buffer.withUnsafeMutableBytes {bufferBytes in
CCCrypt( // Stateless, one-shot encrypt operation
CCOperation(kCCEncrypt), // op: CCOperation
CCAlgorithm(kCCAlgorithmAES), // alg: CCAlgorithm
options, // options: CCOptions
keyBytes.baseAddress, // key: the "password"
key.count, // keyLength: the "password" size
bufferBytes.baseAddress, // iv: Initialization Vector
dataBytes.baseAddress, // dataIn: Data to encrypt bytes
dataToEncrypt.count, // dataInLength: Data to encrypt size
bufferBytes.baseAddress! + kCCBlockSizeAES128, // dataOut: encrypted Data buffer
bufferSize, // dataOutAvailable: encrypted Data buffer size
&numberBytesEncrypted // dataOutMoved: the number of bytes written
)
}
}
}
guard cryptStatus == CCCryptorStatus(kCCSuccess) else {
throw AESError.encryptDataFailed
}
return buffer[..<(numberBytesEncrypted + ivSize)]
}
func decrypt(_ data: Data) throws -> String {
let bufferSize: Int = data.count - ivSize
var buffer = Data(count: bufferSize)
var numberBytesDecrypted: Int = 0
let cryptStatus: CCCryptorStatus = key.withUnsafeBytes {keyBytes in
data.withUnsafeBytes {dataBytes in
buffer.withUnsafeMutableBytes {bufferBytes in
CCCrypt( // Stateless, one-shot encrypt operation
CCOperation(kCCDecrypt), // op: CCOperation
CCAlgorithm(kCCAlgorithmAES128), // alg: CCAlgorithm
options, // options: CCOptions
keyBytes.baseAddress, // key: the "password"
key.count, // keyLength: the "password" size
dataBytes.baseAddress, // iv: Initialization Vector
dataBytes.baseAddress! + kCCBlockSizeAES128, // dataIn: Data to decrypt bytes
bufferSize, // dataInLength: Data to decrypt size
bufferBytes.baseAddress, // dataOut: decrypted Data buffer
bufferSize, // dataOutAvailable: decrypted Data buffer size
&numberBytesDecrypted // dataOutMoved: the number of bytes written
)
}
}
}
guard cryptStatus == CCCryptorStatus(kCCSuccess) else {
throw AESError.decryptDataFailed
}
let decryptedData = buffer[..<numberBytesDecrypted]
guard let decryptedString = String(data: decryptedData, encoding: .utf8) else {
throw AESError.dataToStringFailed
}
return decryptedString
}
}
关于aes - Swift 5 + kCCDecrypt (CommonCrypto) : Failing to decrypt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55484384/
我已经在 nodejs 中重新实现了这个 AES c++ 解密。 “缓冲区”包含加密内容。“decryptKey”包含解密“缓冲区”的 key 。“expectedOutput”包含预期的输出。 为了
我正在尝试解密从后端服务器接收到的字符串 "~9?8?m???=?T?G",该服务器使用 OpenSSL 加密字符串,使用AES-256-CBC。有代码块: public static String
输入图像是被分解为64像素块的灰度图像,加密函数采用64像素(512位)作为输入值和64位密钥。我们将INPUT_VALUE分成8个像素值的块。我们对一组8个像素进行16轮加密。其他每个函数都进行一些
输入图像是被分解为64像素块的灰度图像,加密函数采用64像素(512位)作为输入值和64位密钥。我们将INPUT_VALUE分成8个像素值的块。我们对一组8个像素进行16轮加密。其他每个函数都进行一些
目前我正在使用 PyPDF 2,我也尝试将 PyPDF 4 作为依赖项。 我遇到了一些加密文件并像往常一样处理它们(在以下代码中): import PyPDF2 import PyPDF4 pdfFi
我需要解密 JavaScript 中的十六进制消息,其结果与用 Java 编写的代码完全相同。然而,使用 CryptoJs 的 Javascript 版本返回一个空结果 Java中的代码: priva
我正在设计一个使用加密的匿名聊天网站。我应该在客户端解密消息还是在服务器端解密消息?哪种方法更安全?我使用Node.js + Socket.io来开发聊天系统。 例如: 用户A加密消息,将加密消息发送
这个问题在这里已经有了答案: 8年前关闭。 Possible Duplicate: How come MD5 hash values are not reversible? 我正在阅读一个关于 MD5
因此,我使用以下代码成功将密码加密为密码哈希: class PassHash { // blowfish private static $algo = '$2a'; // co
我不确定,但我认为我的问题是我的函数没有比较字符的正确性。我使用 Switch 也是对的吗? 我的输入 x 是一个字符串,当 x = "aaaaa"时它返回 "aaaaa"而不是 "zzzzz"。 S
我很难逆转这个算法: decrypt_algorithm = function (text) { var parser = new TextParser(text); var decrypt_
我正在编写一个程序,它接受来自控制台的输入 - 一个 zip 文件的名称,一个包含从第一个 zip 生成的(de/en)加密文件的 zip 文件的名称和一个包含公钥。解密时出现异常: exceptio
我正在使用回溯来打印应用程序的堆栈跟踪,我得到类似的东西 libQtCore.so.4(_ZN11QMetaObject8activateEP7QObjectPKS_iPPv+0x843) [0x7f
为什么 Pycrypto AES 解密在使用用于加密的 AES 对象解密时给出不同的输出,而在使用仅用于解密的 AES 对象解密时给出正确的输出? from Crypto.Cipher import
在以下代码中:symmetryCryptoKey 表示应始终受到保护的私有(private)信息,因为它是加密对称 key 的解密版本。 问题: 是否可以进行其他增强来保护 Multi-Tenancy
我正在开展一个项目,部分要求: 添加一个复选框菜单项 Decrypt,可以选中该选项进行解密,也可以取消选中该选项进行加密。该项目应与 GUI 中的切换按钮相关联。两者都应反射(reflect)应用程
我在 ColdFusion 中有一个函数可以加密和解密密码。我需要有人查看该函数并指出我或给我写一个 c# 等效项。一个项目尽快需要它,所以如果你能帮忙的话,我可以通过 paypal 给你一些现金。
我目前正在编写一个非常小的Java程序来实现一次性pad,其中pad(或 key )本身是使用SecureRandom对象生成为一系列字节的,该对象使用一个简单的字符串进行播种SHA-512 算法。
这是我在运行编码和解码类时遇到的错误。 javax.crypto.BadPaddingException: Decryption error at sun.security.rsa.RSAPa
我正在尝试在我的客户端和服务器之间实现基于 RSA 的加密通信。为此,我通过以下方式使用 openssl 生成了 RSA 公钥和私钥: openssl genrsa -out private.pem
我是一名优秀的程序员,十分优秀!