How to encode string (use encrypt MessageDigest in Java) to Base64 string in swift?
Your code does not produce the expected result because the
referenced md5()
function returns the message digest as a
hex-encoded string, which is then Base64 encoded. So instead of
String -> UTF-8 data -> MD5 digest -> Base64 encoding
you are doing
String -> UTF-8 data -> MD5 digest -> hex encoding -> Base64 encoding
A small modification of the function returns the message digest
as data:
func md5(string string: String) -> NSData {
var digest = [UInt8](count: Int(CC_MD5_DIGEST_LENGTH), repeatedValue: 0)
let data = string.dataUsingEncoding(NSUTF8StringEncoding)! // Conversion to UTF-8 cannot fail
CC_MD5(data.bytes, CC_LONG(data.length), &digest)
return NSData(bytes: digest, length: digest.count)
}
Now you can compute the 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 to Base 64 encoded string:
let base64 = md5data.base64EncodedStringWithOptions([])
print("base64 = \(base64)") // base64 = sQqNsWTgdUEFt6mb5y4/5Q==
This is almost what you expect. The Java code apparently produces
the so-called "base64url" variant without padding
(compare https://en.wikipedia.org/wiki/Base64#Variants_summary_table).
Therefore we have to modify two characters and remove the padding:
let base64url = base64
.stringByReplacingOccurrencesOfString("+", withString: "-")
.stringByReplacingOccurrencesOfString("/", withString: "_")
.stringByReplacingOccurrencesOfString("=", withString: "")
print("base64url = \(base64url)") // base64url = sQqNsWTgdUEFt6mb5y4_5Q
Now the result is sQqNsWTgdUEFt6mb5y4_5Q
, and identical to what
you got from the Java code.
Convert UIImage to base64 string in swift
Do it something like this:
For Encoding:
data.base64EncodedStringWithOptions([])
For decoding:
let url = URL(string: String(format:"data:application/octet-stream;base64,%@",base64String))
do {
let data = try Data(contentsOf: url!)
}catch {
}
iOS CryptoKit in Java
This is the final set of code in SWIFT:
let pass = “Password”
let data = “Text to encrypt”.data(using: .utf8)!
let key = SymmetricKey(data: SHA256.hash(data: pass.datat(using: .utf8)!))
let iv = AES.GCM.Nonce()
let mySealedBox = try AES.GCM.seal(data, using: key, nonce: iv)
dataToShare = mySealedBox.combined?.base64EncodedData()
Write this data to a file (I am using google APIs to write this data to a file on google drive)
Read this data from the file in java and pass it to the functions as defined in the question using the below code:
byte[] iv = Base64.getDecoder().decode(text.substring(0,16));
cipher[] = Base64.getDecoder().decode(text.substring(16));
byte[] key = md.digest(pass.getBytes(StandardCharsets.UTF_8));
String plainText = decrypt(cipher, key, iv);
How to decrypt a SHA-256 encrypted string?
SHA-256 is a cryptographic (one-way) hash function, so there is no direct way to decode it. The entire purpose of a cryptographic hash function is that you can't undo it.
One thing you can do is a brute-force strategy, where you guess what was hashed, then hash it with the same function and see if it matches. Unless the hashed data is very easy to guess, it could take a long time though.
You may find the question "Difference between hashing a password and encrypting it" interesting.
Related Topics
Eclipse: Jvm Terminated. Exit Code=2
Why Menuitemcompat.Getactionprovider Returns Null
Cannot Resolve Method Getmap()
Polyline Is Not on the Roads: It Goes Straight from One Point to Other
Noclassdeffounderror on External Library Project for Android
Google Cloud Messaging - Messages Either Received Instantly or with Long Delay
How to Move/Rename File from Internal App Storage to External Storage on Android
Android "Single Top" Launch Mode and Onnewintent Method
Android Buildscript Repositories: Jcenter VS Mavencentral
How to Activate "Share" Button in Android App
Why Do Variable Names Often Start with the Letter 'M'
Recyclerview Scrolled Up/Down Listener
Fragment Add or Replace Not Working
Check Chains of "Get" Calls for Null
Android Resource Not Found Exception
How to Get Ruby Generated Hmac for Sha256 That Is Url Safe to Match Java