How to encode string (use encrypt MessageDigest in Java) to Base64 string in swift? -
in java, used this:
public void encryptdata() { string data = "hello world"; messagedigest md = null; try { md = messagedigest.getinstance("md5"); } catch (nosuchalgorithmexception e) { e.printstacktrace(); } if (md == null) { return; } md.update(data.getbytes()); string dataencoded = base64.encodetostring(md.digest(), 11); return dataencoded; //print: sqqnswtgdueft6mb5y4_5q }
how do have same results in swift?
updated:
func test() -> void { var data: string = "hello world" data = md5(data) data = base64encode(data) print("data = \(data)") //yjewythkyje2nguwnzu0mta1yjdhotliztcyztnmztu= }
md5 , base64encode function used md5 here , base64 here
any hints helpful.
your code not produce expected result because referenced md5()
function returns message digest hex-encoded string, base64 encoded. instead of
string -> utf-8 data -> md5 digest -> base64 encoding
you doing
string -> utf-8 data -> md5 digest -> hex encoding -> base64 encoding
a small modification of function returns message digest data:
func md5(string string: string) -> nsdata { var digest = [uint8](count: int(cc_md5_digest_length), repeatedvalue: 0) let data = string.datausingencoding(nsutf8stringencoding)! // conversion utf-8 cannot fail cc_md5(data.bytes, cc_long(data.length), &digest) return nsdata(bytes: digest, length: digest.count) }
now can compute base 64 encoded md5 digest:
let string = "hello world" // compute md5 message digest: let md5data = md5(string: string) print("md5data = \(md5data)") // md5data = <b10a8db1 64e07541 05b7a99b e72e3fe5> // convert base 64 encoded string: let base64 = md5data.base64encodedstringwithoptions([]) print("base64 = \(base64)") // base64 = sqqnswtgdueft6mb5y4/5q==
this almost expect. java code apparently produces so-called "base64url" variant without padding (compare https://en.wikipedia.org/wiki/base64#variants_summary_table).
therefore have modify 2 characters , remove padding:
let base64url = base64 .stringbyreplacingoccurrencesofstring("+", withstring: "-") .stringbyreplacingoccurrencesofstring("/", withstring: "_") .stringbyreplacingoccurrencesofstring("=", withstring: "") print("base64url = \(base64url)") // base64url = sqqnswtgdueft6mb5y4_5q
now result sqqnswtgdueft6mb5y4_5q
, , identical got java code.
Comments
Post a Comment