Can't convert encrypted data to String - swift

I am trying to learn to use RNCryptor. Here is what I am using:
let key = "1234"
let original_text = "hello"
let data = original_text.data(using: .utf8)!
let encrypted_data = RNCryptor.encrypt(data: data, withPassword: key)
print(String(data: encrypted_data, encoding: .utf8))
This prints 'nil'. How can I convert encrypted_data to a String?
Also, this does work:
try! print(String(data: RNCryptor.decrypt(data: encrypted_data, withPassword: key), encoding: .utf8))
but this is the original text and not the cipher text.

The encrypted data is a binary blob, and in most cases not a valid
UTF-8 sequence. Therefore the conversion to a string
String(data: encrypted_data, encoding: .utf8)
fails and returns nil. If you want a string representation of the
encrypted data then you can use (for example) the Base64 encoding:
print(encrypted_data.base64EncodedString())
or, using
extension Data {
func hexEncodedString() -> String {
return map { String(format: "%02hhx", $0) }.joined()
}
}
from How to convert Data to hex string in swift, as a hex-encoded string:
print(encrypted_data.hexEncodedString())

Related

RSAUtils Decryption , Converting data to it's original value - Swift

i am trying to encrypt and decrypt a string using RSAUtils swift library, i am having a problem returning the decrypted text to it's original value . this is the code:
let PUBLIC_KEY = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJh+/sdLdlVVcM5V5/j/RbwM8SL++Sc3dMqMK1nP73XYKhvO63bxPkWwaY0kwcUU40+QducwjueVOzcPFvHf+fECAwEAAQ=="
let sampleText:String = "WHATS UP"
let encrypted:Data? = RSAUtils.encryptWithRSAPublicKey(sampleText.data(using: String.Encoding.utf8)!, pubkeyBase64: PUBLIC_KEY, keychainTag: "12345")!
let decrypted:Data? = RSAUtils.decryptWithRSAPublicKey(encrypted!, pubkeyBase64: PUBLIC_KEY, keychainTag: "12345")
let encryptedDataText = encrypted!.base64EncodedString(options: NSData.Base64EncodingOptions())
let decryptedDataText = decrypted!.base64EncodedString(options: NSData.Base64EncodingOptions())
I tried to convert the decrypted data to string using this code:
if let string = String(data: decrypted! , encoding: .utf16) {
print(string)
} else {
print("not a valid UTF-16 sequence")
}
But it prints "㺸ꉄ꤈꽹㲞㏯荘뼵鉉큅령嬰ꢤẲ毪쌶⏤ᱼ埡佒�ࡊᩏ⧚㨈؍੯屍" I also tried to decode the base64 value using :
let decodedData = Data(base64Encoded: decryptedDataText)!
let decodedString = String(data: decodedData, encoding: .utf8)!
print(decodedString)
It causes an error
Fatal error: Unexpectedly found nil while unwrapping an O
probably the text is not a valid base64 string.
How can i convert the decrypted data to it's original value.
Thanks.

data from base64 url

I have a URL in the form of
foo://?data:application/x-foo;base64,OjAyMDAwMDA0MDAwMEZBDQo6MTAwMDA...
and now need to extract the base64 data into a Data object.
Unfortunately it seems the Data object does not support this yet as
let data = try Data(contentsOf: url)
returns NSURLConnection finished with error - code -1002 when trying.
While I could decode the URL manually I am wondering if I am missing a simple standard way of doing this. How would you do this?
Actually you can decode Base64 data from an URL (see for
example Base64 Decoding in iOS 7+ where this is demonstrated in Objective-C). The format is a bit different from what
you have:
let url = URL(string: "data:application/octet-stream;base64,SGVsbG8gd29ybGQh")!
let data = try! Data(contentsOf: url)
print(String(data: data, encoding: .utf8)!) // Hello world!
(Error checking omitted for brevity.)
You have to separate the base64 encoded part of the URL from the other parts, decode it, then join the original non-encoded part with the decoded part and get the data from there.
extension URL {
init?(partialBase64Url: String){
guard let base64part = base64Url.components(separatedBy: "base64,").last, let base64Data = Data(base64Encoded: base64part), let decodedString = String(data: base64Data, encoding: .utf8) else {
return nil
}
let decodedUrl = base64Url.components(separatedBy: "base64,").dropLast().joined() + decodedString
self.init(string: decodedUrl)
}
}
let decodedUrl = URL(partialBase64Url: "foo://?data:application/x-foo;base64,dGVzdFVybFN0cmluZw==")
Value of decodedUrl: "foo://?data:application/x-foo;testUrlString", as expected, since dGVzdFVybFN0cmluZw== is the base64 encoded value of testUrlString.

Decrypt from Base64 format (Swift)

Here is Encrypted string using Base64 ->
(ew0KICAiTmV3c0dyYXBoIjogWw0KICAgIHsNCiAgICAgICJEYXRlIjogIjA0LUZlYiIsDQogICAgICAiTmV3c1Njb3JlIjogNTAuMCwNCiAgICAgICJUYWJsZU5hbWUiOiAiTmV3c0dyYXBoIg0KICAgIH0sDQogICAge)
and Here is the extension method to Decrypt the string
extension String
{
func fromBase64() -> String
{
let data = NSData.init(base64Encoded: self, options: []) ?? NSData()
return String(data: data as Data, encoding: String.Encoding.utf8) ?? ""
}
}
There is no output in my Text View, but you will get decrypted output for the same string on -> https://www.base64decode.org
But if i took substring from the encrypted string ->
ew0KICAiTmV3c0dyYXBoIjogWw0KICAgIHsNCiAgICAgICJEYXRlIjogIjA0LUZlYiIsDQogICAgICAiTmV3c1Njb3JlIjogNTAuMCwNCiAgICAgICJUYWJsZU5hbWUiOiAiTmV3c0dyYXBoIg0KICAgIH0sDQog
then my code returns decrypted string.
What is the issue?
can any one please
Base64 is not encryption, it is an encoding.
The length is incorrect ignoring the enclosing parenthesis, Base64 encoding must be a multiple of 4 characters.
Example:
Deleting the last character to create a valid length.
First decode the Base64 string to Data, then encode to aUTF-8 string.
let base64 = "ew0KICAiTmV3c0dyYXBoIjogWw0KICAgIHsNCiAgICAgICJEYXRlIjogIjA0LUZlYiIsDQogICAgICAiTmV3c1Njb3JlIjogNTAuMCwNCiAgICAgICJUYWJsZU5hbWUiOiAiTmV3c0dyYXBoIg0KICAgIH0sDQogICAg"
let decodedData = Data(base64Encoded: base64)!
let decodedString = String(data: decodedData, encoding: .utf8)
print(decodedString!)
Result:
{
"NewsGraph": [
{
"Date": "04-Feb",
"NewsScore": 50.0,
"TableName": "NewsGraph"
},
It would seem that Base64 string in the question is incomplete and has been truncated.

Swift 2 Decode base64 always return nil

I'm trying to decode the following string from base64 without any exit. It always returns nil. I have tried to change NSDataBase64DecodingOptions to IgnoreUnknowCharanters but it doesn't work either. I also tried to remove the padding like this answer says swift base64 decoding returns nil but the length of my string is divisible by 4 so It doesn't works.
string
PY5ehymWfQKExWxPyOImGiQkxNjyuBREmOXtQdePVpuH9PFzizaO+WTuM1sLouTQPz5UO7csloC9GjOFqkq4POmlB9d3mMJGLB2pVCNs8t9EejOcjV4fRHaITkmfMfVbizCnTvHGBwLWXjLc7gwyhu2+S9qw0NXc5jw6EdEk+zuesrdwLgqws0hDqFSoVw57+CnvUmgXwtNfKP4p64mJ9inH/0xAMarCc5N4Wjz/zmlTyd2PoDFUC/iLdZ7csau7X2M=
option 1
if let decodedData = NSData(base64EncodedString: base64String, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters),
let decodedString = NSString(data: decodedData, encoding: NSUTF8StringEncoding) {
print(decodedString) // foo
}
option 2
if let decodedData = NSData(base64EncodedString: pnpData, options: NSDataBase64DecodingOptions.init(rawValue: 0)),
let decodedString = NSString(data: decodedData, encoding: NSUTF8StringEncoding) {
print(decodedString) // foo
}
Hope you can help me. Thanks!!
Just in case someone is trying to Solve this issue moving from Java to Swift.
This Answer helped me out, you might need to append("==")
Swift 3 base64 decode return nil
You might need to append("==")
I doubt on string "PY5ehymWfQKExWxPyOImGiQkxNjyuBREmOXtQdePVpuH9PFzizaO+WTuM1sLouTQPz5UO7csloC9GjOFqkq4POmlB9d3mMJGLB2pVCNs8t9EejOcjV4fRHaITkmfMfVbizCnTvHGBwLWXjLc7gwyhu2+S9qw0NXc5jw6EdEk+zuesrdwLgqws0hDqFSoVw57+CnvUmgXwtNfKP4p64mJ9inH/0xAMarCc5N4Wjz/zmlTyd2PoDFUC/iLdZ7csau7X2M="
This works, that string getting encode and decode too
let utf8str = "PY5ehymWfQKExWxPyOImGiQkxNjyuBREmOXtQdePVpuH9PFzizaO+WTuM1sLouTQPz5UO7csloC9GjOFqkq4POmlB9d3mMJGLB2pVCNs8t9EejOcjV4fRHaITkmfMfVbizCnTvHGBwLWXjLc7gwyhu2+S9qw0NXc5jw6EdEk+zuesrdwLgqws0hDqFSoVw57+CnvUmgXwtNfKP4p64mJ9inH/0xAMarCc5N4Wjz/zmlTyd2PoDFUC/iLdZ7csau7X2M=".dataUsingEncoding(NSUTF8StringEncoding)
let base64Encoded = utf8str?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
let encodedString : String = base64Encoded!
print(encodedString) // my encoded data
let decodedData = NSData(base64EncodedString: encodedString, options:NSDataBase64DecodingOptions(rawValue: 0))
let decodedString : String = String(data: decodedData!, encoding: NSUTF8StringEncoding)!
print(decodedString) // my plain data
This doesn't work, that decoded string dont get encode
let decodedData = NSData(base64EncodedString: "PY5ehymWfQKExWxPyOImGiQkxNjyuBREmOXtQdePVpuH9PFzizaO+WTuM1sLouTQPz5UO7csloC9GjOFqkq4POmlB9d3mMJGLB2pVCNs8t9EejOcjV4fRHaITkmfMfVbizCnTvHGBwLWXjLc7gwyhu2+S9qw0NXc5jw6EdEk+zuesrdwLgqws0hDqFSoVw57+CnvUmgXwtNfKP4p64mJ9inH/0xAMarCc5N4Wjz/zmlTyd2PoDFUC/iLdZ7csau7X2M=", options:NSDataBase64DecodingOptions(rawValue: 0))
let decodedString : String = String(data: decodedData!, encoding: NSUTF8StringEncoding)!
print(decodedString) // my plain data
This could be reason, check on https://www.base64decode.org/
Though special characters can't be hold in String.
maybe you can follow this
https://github.com/krzyzanowskim/CryptoSwift#data-padding
and use following method to decode(i guess your string is encoded by aes cbc and base64, if you want to decode this string, you must know the encode key and iv)
"PY5ehymWfQKExWxPyOImGiQkxNjyuBREmOXtQdePVpuH9PFzizaO+WTuM1sLouTQPz5UO7csloC9GjOFqkq4POmlB9d3mMJGLB2pVCNs8t9EejOcjV4fRHaITkmfMfVbizCnTvHGBwLWXjLc7gwyhu2+S9qw0NXc5jw6EdEk+zuesrdwLgqws0hDqFSoVw57+CnvUmgXwtNfKP4p64mJ9inH/0xAMarCc5N4Wjz/zmlTyd2PoDFUC/iLdZ7csau7X2M=".decryptBase64ToString(cipher)

swift aes 128 decryption with string input

I'm using zaph's example for encryption and decryption from this post
The encryption works well, and with my encryption key and iv, returns an NSData object, containing the following string: "bc6983a8 65d412df 2bafdc40 f569874e", which is my input text encrypted. The content of the returned NSData object:
encrypted text: <bc6983a8 65d412df 2bafdc40 f569874e>
This text is sent to a server (json), and the server returns a response, also encrypted with the same encryption key and iv.
My question is, how can I convert the string text that comes from the server's response(bc6983a8 65d412df 2bafdc40 f569874e, for example) into an NSData object so that i can decrypt it?
I tried the follwing:
let plainData = ("<bc6983a8 65d412df 2bafdc40 f569874e>" as NSString).dataUsingEncoding(NSUTF8StringEncoding)!;
let plainData = ("<bc6983a8 65d412df 2bafdc40 f569874e>" as NSString).dataUsingEncoding(NSUTF8StringEncoding)!;
let base64String = plainData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0));
let dataDec = NSData(base64EncodedString: base64String, options: NSDataBase64DecodingOptions(rawValue: 0))
But when displaying the contents of the NSData object, the output is not the one expected:
data Optional("<3c626336 39383361 38203635 64343132 64662032 62616664 63343020 66353639 38373465 3e>")
Any help is appreciated.
You are converting your NSData to the string in a wrong way. Follow this code to convert NSData to string
//This is your encrypted data
var encryptedData = NSData()
let plainData = encryptedData(data: encryptedData, encoding: NSUTF8StringEncoding)
Hope this will work for you.
UPDATE:
This happens because you are not correctly fetching the string from your backend. Use proper method for decoding json data instead of just printing it. "<bc6983a8 65d412df 2bafdc40 f569874e>" is not the string you actually need. You need to decode your json data
See the sample code
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil
{
print("error=\(error)", terminator: "")
return
}
do{ if let newdata = try? (NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary)
{
print(newdata)
}
Here 'newdata' may include the encrypted string you need. Parse it from that json, convert it to NSData and then decrypt.
UPDATE 2
Use this code to convert your data to string
let resstr = NSString(data: YourData, encoding: NSUTF8StringEncoding)