如何在ios,swift中使用RSA公钥加密和解密字符串(纯文本)



我想用我的RSA公钥Encrypt一个字符串(纯文本(。我有一个public key,它作为String从服务器发送,并以此创建了一个RSA公钥。现在我想使用该键Encrypt带有填充PKACS12的文本。我怎么能这样做。我经历了很多堆栈溢出问题,但没有取得任何成功。

这就是我创建RSA public key的方式,

let serverPublicKey = "Some text with key"
let data2 = Data.init(base64Encoded: serverPublicKey)
let keyDict:[NSObject:NSObject] = [
kSecAttrKeyType: kSecAttrKeyTypeRSA,
kSecAttrKeyClass: kSecAttrKeyClassPublic,
kSecAttrKeySizeInBits: NSNumber(value: 2048),
kSecReturnPersistentRef: true as NSObject
]
let publickeysi = SecKeyCreateWithData(data2! as CFData, keyDict as CFDictionary, nil)

这将成功创建RSA public key。 现在我想用这个密钥来加密我的另一个Plain Text。 我该怎么做。

希望这对您有所帮助:

let serverPublicKey = "Some text with key"
let data2 = Data.init(base64Encoded: serverPublicKey)
let keyDict:[NSObject:NSObject] = [
kSecAttrKeyType: kSecAttrKeyTypeRSA,
kSecAttrKeyClass: kSecAttrKeyClassPublic,
kSecAttrKeySizeInBits: NSNumber(value: 2048),
kSecReturnPersistentRef: true as NSObject
]
let publickeysi = SecKeyCreateWithData(data2! as CFData, keyDict as CFDictionary, nil)
//Encrypt a string with the public key
let message = "This is my message."
let blockSize = SecKeyGetBlockSize(publickeysi!)
var messageEncrypted = [UInt8](repeating: 0, count: blockSize)
var messageEncryptedSize = blockSize
var status: OSStatus!
status = SecKeyEncrypt(publickeysi!, SecPadding.PKCS1, message, message.characters.count, &messageEncrypted, &messageEncryptedSize)
if status != noErr {
print("Encryption Error!")
return
}
import Foundation
import Security

struct RSA {
static func encrypt(string: String, publicKey: String?) -> String? {
guard let publicKey = publicKey else { return nil }
let keyString = publicKey.replacingOccurrences(of: "-----BEGIN RSA PUBLIC KEY-----n", with: "").replacingOccurrences(of: "n-----END RSA PUBLIC KEY-----", with: "")
guard let data = Data(base64Encoded: keyString) else { return nil }
var attributes: CFDictionary {
return [kSecAttrKeyType         : kSecAttrKeyTypeRSA,
kSecAttrKeyClass        : kSecAttrKeyClassPublic,
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 encrypt(string: string, publicKey: secKey)
}
static func encrypt(string: String, publicKey: SecKey) -> String? {
let buffer = [UInt8](string.utf8)
var keySize   = SecKeyGetBlockSize(publicKey)
var keyBuffer = [UInt8](repeating: 0, count: keySize)
// Encrypto  should less than key length
guard SecKeyEncrypt(publicKey, SecPadding.PKCS1, buffer, buffer.count, &keyBuffer, &keySize) == errSecSuccess else { return nil }
return Data(bytes: keyBuffer, count: keySize).base64EncodedString()
}
}

像这样使用

var pemString = "-----BEGIN RSA PUBLIC KEY-----nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAl/zjMK4w1XZAnpIqLeTAMW7cEUNIifP3HjmUavvc2+oPG1QjNCfxQM6LulZSl6qRim2JGxbc3yvnbMRJqch6IhJ/ysbTekVSqOjskIRGxq0pg0J8PqF3ZZQK6D7BYHi6iaJUMVV0ISB5LogJouyOWqsZyiEjgPz3jj0HIrh14Q6wPZVMpVbIwQR9nZp5gU5minseCyZfQs3PArgXgnzRPdw7Hb0/NY5OVE2Rz1SFTnda6w12SEu1IsVhVhJz1QteNrwNwJAT6WgZd+xnOZhU3Ei+EQK2SijfEGqmWNt1utJygK/0APy8w7VTol7ygbqfuHevGcg90QEXjxZKCjkXkQIDAQABn-----END RSA PUBLIC KEY-----"

let password = "abcdefg"
let encryptedPassword = RSA.encrypt(string: password, publicKey: pemString)
print(encryptedPassword)

相关内容

  • 没有找到相关文章

最新更新