我在swift 3中使用SWCrypt。我以base64字符串格式获取服务器公钥。我应该用服务器公钥解密这个JSON文件。
{ "address":"asdf", "city": "asdf", "telephone": "345435", "zipCode": "1235458", "mobile":"3453245" }
在RSA解密和加密方法中公共私钥类型是DATA,我尝试将服务器公钥转换为数据但我无法加密数据并得到解码错误。
我的代码是创建公钥和加密数据。我在尝试加密数据时遇到此代码的解码错误。
@IBAction func generateKey(_ sender: Any) {
do {
let (privateKey, publicKey) = try CC.RSA.generateKeyPair(2048)
let privateKeyPEM = SwKeyConvert.PrivateKey.derToPKCS1PEM(privateKey)
let publicKeyPEM = SwKeyConvert.PublicKey.derToPKCS8PEM(publicKey)
privatePem = privateKeyPEM
publicPem = publicKeyPEM
print("this is generate public pem : \(publicPem!)")
}
catch {
print(error.localizedDescription)
}
}
@IBAction func createDataOfServerKey(_ sender: Any) {
var serverKey : String = self.serverKey.text!
serverKey = serverKey.replacingOccurrences(of: "+", with: "%2d", options: .literal, range: nil)
serverKey = serverKey.replacingOccurrences(of: "/", with: "%2d", options: .literal, range: nil)
// let datakey = NSData(base64Encoded: serverKey, options: .init(rawValue: 0))
let dataKey = serverKey.data(using: .utf8)
if let data = dataKey {
serverKeyData = data
}
}
@IBAction func encryptJson(_ sender: Any) {
let json = jsonData.text
let s = json!.data(using: .utf8)
do {
let encrypt = try CC.RSA.encrypt(s!, derKey: serverKeyData!, tag: s!, padding: .pkcs1, digest: .md5)
publicPem64.text = encrypt.base64EncodedString(options: [])
print("this is encrypt json : \(publicPem64.text)")
print(publicPem64.text.characters.count)
view.layoutIfNeeded()
}
catch {
print(error.localizedDescription)
}
}
此代码工作并返回加密数据,然后我将此结果base64string发送到服务器,但我无法得到任何响应。
@IBAction func createDataOfServerKey(_ sender: Any) {
var serverKey : String = self.serverKey.text!
let datakey = NSData(base64Encoded: serverKey, options: .init(rawValue: 0))
if let data = dataKey {
serverKeyData = data
}
}
另外在android中使用un_wrap base64解码。