神勇威武的豆浆 · swift:使导航栏从右到左(rtl)与左右 ...· 4 天前 · |
精明的核桃 · 国泰航空扭亏为盈,月薪2万港元招内地驻港空乘 ...· 1 月前 · |
文质彬彬的红豆 · 许昌两位校长,两位老师入选这份名单!_教育· 1 月前 · |
自信的登山鞋 · 检察榜样·人民满意的公务员|驻村书记的鱼水情 ...· 1 月前 · |
谈吐大方的刺猬 · 豆官和琪官-西瓜视频搜索· 5 月前 · |
腼腆的绿豆 · 东风启辰D60 ...· 1 年前 · |
我有一些来自Java的方法,需要在Swift中实现:
fun encryptMessage(content: String): String {
val cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING")
cipher.init(Cipher.ENCRYPT_MODE, publicKey)
val encryptedBytes = cipher.doFinal(content.toByteArray())
val encryptedData = Base64.encodeToString(encryptedBytes, Base64.DEFAULT)
return ENCRYPT_MARK + encryptedData
fun decryptMessage(content: String): String {
val cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING")
cipher.init(Cipher.DECRYPT_MODE, privateKey)
var encryptedData = Base64.decode(content.substring(ENCRYPT_MARK.length), Base64.DEFAULT)
val decryptedBytes = cipher.doFinal(encryptedData)
return String(decryptedBytes)
}
我对加密和解密不是很在行。我尝试了我找到的几个库和代码,但没有对我有效。
我需要解密的示例字符串:
"p+KuB7UVUteY8g3HVMxo+7h2xhZQxhPjPayMolqq8EYyIknbQjgqHjC95NR8/le6G0F8SQACrOdj\nTlPU1+o7bZrE8ukI7B35i9sWZns3Y2scA9U7yz8z5KsTZ240+4+Xd7dZwfQ49Z6J7nNOfBR/97pq\n2l1QKe0/SThUEraZyts=\n"
我的私钥:
"-----BEGIN RSA PRIVATE KEY-----\nMIICXQIBAAKBgQDjOUZOZgIYWDMkyhyNb/gsFUDbDB3a+FWwT0d2HE7cd3bqebYLg\nKAMqwpc8nCHR77kO23Nd/U5WKVWwFcHUQVtkMcX4QNDtxSV72LRNaSaQZkwBofw9O\nu338mm1hR0DEYzYPXKuyaP3l5/pvZyvOHrA+i0ZD7pUohEtiDsuNhZbwIDAQABAoG\nBAJoM6q2cWy9GHOaEYHdDwm2guyfHPzaFxxKRrVFWP+EY3XZ6rgF+YwQzsgLyG3ic\nG7+AyyDSg18tymrWXCqJs7Mdrxq3xZmdCzwTcfgxZcwiFG0caK/jbA8rXO60xecag\nZRR+AyWa+2wnwt5xPtFcqk7GhqkWIolzQddW7L3CIuBAkEA9Xw+fnLrbR3WaxTpa3\n88NEEgvyxIS2eGc+lRUbC8w2xX5qDtV8Ak7rxkmXGURJ6tvwyUi/Q+5y+X20mBtt8\nsKwJBAOz0yph9n4iHtC+BL5U+LfpZuUO6uUctbmfXs+fU2glI8rAwXhanBCs0Ph/0\nG7aXmNKHvcSjQ9N5mhTPBvhpcc0CQH4PPTBF5ytzZQY8CNmQzuOuhhhlrwI5uUuQh\npfCgEyCOGlQPlEPdGe8CpTZRGAwc9xlo2pzFFI3mG2dQ6Ua2V0CQQCSMY11e7wbzi\n37SScEWzKezRCimueI5JzDcK/MjuRe6iThU1YZf73wsfDKYh9fDjT5X0pTsa89ID9\nSK1DPnq7ZAkB6ybvpomovyBBgSjjTEwwSHyAIr5HIE2hkDjer6/87/WNKEw1yg11b\ngSoJC67f1xnLj7bv9/EJRPWTokCaRRm/\n-----END RSA PRIVATE KEY-----"
1. SecKeyCreateDecryptedData
let encryptedMessageData = encryptedMessage.data(using: .utf8)
if let decryptedMessage:Data = SecKeyCreateDecryptedData(privateSecKey!, .rsaEncryptionPKCS1, encryptedMessageData as CFData, error) as Data? {
print("We have an decrypted message \(String.init(data: decryptedMessage, encoding: .utf8)!)")
} else {
print("Error decrypting")
}
中没有错误。
2. SwiftyRSA
let encrypted = try EncryptedMessage(data: key.data(using: .utf8)!) // try EncryptedMessage(base64Encoded: key)
let privateKey = try PrivateKey(pemEncoded: keyPair.privateKey)
let decryptedKey = try encrypted.decrypted(with: privateKey, padding: SecPadding.PKCS1)
3. CryptorRSA
let data = base64.data(using: .utf8)!
let encryptedData = try CryptorRSA.createEncrypted(with: data)
let decryptedData = try encryptedData.decrypted(with: privateKey, algorithm: .sha1)
错误Domain=NSOSStatusErrorDomain代码=-50 "RSAdecrypt错误输入(err -27)“UserInfo={numberOfErrorsDeep=0,NSDescription=RSAdecrypt错误输入(err -27)}
我甚至尝试用这些代码行来实现解密,但没有成功:
static func decrypt(string: String, privateKey: String?) -> String? {
guard let privateKey = privateKey else { return nil }
let keyString = privateKey.replacingOccurrences(of: "-----BEGIN RSA PRIVATE KEY-----\n", with: "").replacingOccurrences(of: "\n-----END RSA PRIVATE KEY-----", with: "")
guard let data = Data(base64Encoded: keyString, options: .ignoreUnknownCharacters) else { return nil }
var attributes: CFDictionary {
return [kSecAttrKeyType : kSecAttrKeyTypeRSA,
kSecAttrKeyClass : kSecAttrKeyClassPrivate,
kSecAttrKeySizeInBits : 2048,
kSecReturnPersistentRef : true] as CFDictionary
var error: Unmanaged<CFError>? = nil
guard let secKey = SecKeyCreateWithData(data as CFData, attributes, &error) else {
print(error.debugDescription)
return nil
return decrypt(string: string, privateKey: secKey)
static func decrypt(string: String, privateKey: SecKey) -> String? {
let buffer = [UInt8](string.utf8)
let keySize = SecKeyGetBlockSize(privateKey)
var messageDecrypted = [UInt8](repeating: 0, count: keySize)
var messageDecryptedSize = keySize
var status = SecKeyDecrypt(privateKey, SecPadding.PKCS1, buffer, buffer.count, &messageDecrypted, &messageDecryptedSize)
if status != noErr {
print("Decryption Error!")
return nil
let result = String(bytes: messageDecrypted, encoding: .utf8)
print(result)
return result
}
我做错了什么?我如何解密这些示例数据?谢谢你的帮助
发布于 2021-05-18 22:35:17
下面,您将看到一个使用随机生成的密钥进行加密和解密的快速示例。为了简单起见,我添加了bang操作符,但它可能只是向您展示了如何使用Swift中的RSA加密和解密数据。
let attributes = [
kSecAttrKeyType: kSecAttrKeyTypeRSA,
kSecAttrKeySizeInBits: 2048,
kSecAttrKeyClass: kSecAttrKeyClassPrivate
] as CFDictionary
var error: Unmanaged<CFError>?
let privateKey = SecKeyCreateRandomKey(attributes, &error)!
let publicKey = SecKeyCopyPublicKey(privateKey)!
let message = Data("Hello World".utf8)
let ciphertext = SecKeyCreateEncryptedData(publicKey, .rsaEncryptionPKCS1, message as CFData, &error)! as Data
print(ciphertext as NSData)