通过SwiftyRSA对数据进行加密
第一步:导入库文件
pod 'SwiftyRSA', "~> 1.7.0"
pod 'CryptoSwift', "~> 1.8.3"
第二步:编辑代码
iimport UIKit
import SwiftyRSA
import CryptoSwift
let PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArdklK4kIsOMuxTZ8jG1PRPfXqSDmaCIQ+xEpIRSssQ6jiuvhYZTMUbV22osgtivuyKdnHm+cvzGuZCSB8QFyCcM7l09HZVs0blLkrBAU5CVSv+6BzPQTVJytoi/VO4mlf6me1Y9bXWrrPw1YtC1mnB2Ix9cuaxOLpucglfGbUaGEigsUZMTD2vuEODN5cJi39ap+G9ILitbrnt+zsW9354pokVnHw4Oq837Fd7ZtP0nAA5F6nE3FNDGQqLy2WYRoKC9clDecD8T933azUD98b5FSUGzIhwiuqHHeylfVbevbBW91Tvg9s7vUMr0Y2YDpEmPAf0q4PlDt8QsjctT9kQIDAQAB"
let PRIVATE_KEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCt2SUriQiw4y7FNnyMbU9E99epIOZoIhD7ESkhFKyxDqOK6+FhlMxRtXbaiyC2K+7Ip2ceb5y/Ma5kJIHxAXIJwzuXT0dlWzRuUuSsEBTkJVK/7oHM9BNUnK2iL9U7iaV/qZ7Vj1tdaus/DVi0LWacHYjH1y5rE4um5yCV8ZtRoYSKCxRkxMPa+4Q4M3lwmLf1qn4b0guK1uue37Oxb3fnimiRWcfDg6rzfsV3tm0/ScADkXqcTcU0MZCovLZZhGgoL1yUN5wPxP3fdrNQP3xvkVJQbMiHCK6ocd7KV9Vt69sFb3VO+D2zu9QyvRjZgOkSY8B/Srg+UO3xCyNy1P2RAgMBAAECggEAInVN9skcneMJ3DEmkrb/5U2yw2UwBifqcbk/C72LVTTvmZOTgsH5laCARGUbQMCIfeEggVniGcuBI3xQ/TIqJmE6KI2gOyjOxadMiAZP/cCgHEbsF3Gxey3rBKCyhTCN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N//1UOY"
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let rsa = rsa_encrypt("1212121212121")
print("加密数据 = \(rsa)")
let rsa2 = rsa_decrypt(rsa)
print("解密数据 = \(rsa2)")
}
///rsa加密
func rsa_encrypt(_ str:String) -> String{
var reslutStr = ""
do{
let rsa_publicKey = try PublicKey(pemEncoded: PUBLIC_KEY)
let clear = try ClearMessage(string: str, using: .utf8)
reslutStr = try clear.encrypted(with: rsa_publicKey, padding: .PKCS1).base64String
}catch{
print("RSA加密失败 - \(error)")
}
return reslutStr;
}
///rsa解密
func rsa_decrypt(_ str:String) -> String{
var reslutStr = ""
let enData = Data(base64Encoded: str, options: .ignoreUnknownCharacters)!
do{
let rsa_privateKey = try PrivateKey(pemEncoded: PRIVATE_KEY)
let data = try EncryptedMessage(data: enData).decrypted(with: rsa_privateKey, padding: .PKCS1).data
reslutStr = String(bytes: data.bytes, encoding: .utf8) ?? ""
}catch{
print("RSA解密失败")
}
return reslutStr
}
}
第三步
打印结果
加密数据 = fJR9Z/m1t+X5pee0dcWtMosRcY1i+1d2HLKnOhOoUQ4aCQo91dksZlw7FUY7jsZXkqrVrbViRxQby7y9bYafUUvwgz2YdnoyoMxt3EHeXwSJoyEzB+y4g17dPu7RbScrMWWTZZVtWdEkuG4rdcKjiKNzJn9vQ1JgdiGWARQJUkV6ttkdIMD69gKXwbXg+f1oVLKRq1TWgLpC+qtSVsBIMTFb+4ancdqw3CDt4bUzgDXocInTzBFC0BNy7q6Mnjm+KfIL7Jq3TUXVJLlkqX0Qwq/HnkXuzjaeG+S6mchNDBgfkmD8rTezFZxNJWk8DEqVaO9iwCdr6PcJx8LvCZZmwQ==
解密数据 = 1212121212121