I'm working on 1 iOS app which gets encrypted data from API. I have tried converting JS code to the swift, but have not been able to do it. I'm stuck at the decryption part, in a later stage, I have to again encrypt it for API requests. JS Code is below:
function hexToBase64(str) {
return btoa(String.fromCharCode.apply(null,
str.replace(/\r|\n/g, "").replace(/([\da-fA-F]{2}) ?/g, "0x$1 ").replace(/ +$/, "").split(" "))
);
}
function base64ToHex(str) {
for (var i = 0, bin = atob(str.replace(/[ \r\n]+$/, "")), hex = []; i < bin.length; ++i) {
var tmp = bin.charCodeAt(i).toString(16);
if (tmp.length === 1) tmp = "0" + tmp;
hex[hex.length] = tmp;
}
return hex.join("");
}
export function decryptFuncForNet(transitmessage, pass) {
var hexResult = base64ToHex(transitmessage)
var salt = CryptoJS.enc.Hex.parse(hexResult.substr(0, 64));
var iv = CryptoJS.enc.Hex.parse(hexResult.substr(64, 32));
var encrypted = hexToBase64(hexResult.substring(96));
var key = CryptoJS.PBKDF2(pass, salt, {
keySize: keySize / 32,
iterations: iterations
});
var decrypted = CryptoJS.AES.decrypt(encrypted, key, {
iv: iv,
padding: CryptoJS.pad.Pkcs7,
mode: CryptoJS.mode.CBC
})
return decrypted.toString(CryptoJS.enc.Utf8);
}
Can someone help me to convert it to swift functions? Or is there any pod/framework available for this?
Thank you in advance.
you could try something like this for hexResult:
func hexToBase64(_ str: String) -> String {
let hexdata = str.data(using: .utf8)!
return hexdata.base64EncodedString()
}
func base64ToHex(_ str: String) -> String? {
if let dataHex = Data(base64Encoded: hexResult),
let decodedHex = String(data: dataHex, encoding: .utf8) {
return decodedHex
}
return nil
}
// encrypt
let transitmessage = "BA5E64C0DE"
print("---> transitmessage: \(transitmessage)")
let hexResult = hexToBase64(transitmessage)
print("---> hexResult: \(hexResult)")
// decrypt
if let decodedHex = base64ToHex(hexResult) {
print("---> decodedHex: \(decodedHex) \n")
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.