How does this work in terms of data variability in bytes? - swift

let keyData: NSData! = (keyString as NSString).data(using: String.Encoding.utf8.rawValue) as NSData!
What would keyData amount to in terms of bytes if keyString = "1234567890000000000000000"?
What can I do to see the value of keyData or print it to the console?
Also, how can I get the keyString back from keyData in Swift?
Can someone please explain what is going on in here in this expression? I cannot seem to get my head around it. Thanks in advance.

The number of bytes will depend on the encoding you used to convert string to data. Below are the answers to each question
1) print(keyData.length)
2) print(String(data: keyData as Data, encoding: .utf8)!)
3) let string = String(data: keyData as Data, encoding: .utf8)!

Related

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.

Can't convert encrypted data to String

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())

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)

How to change GB-2312 encoding to UTF-8

I use nsurlsession and received nsdata with GB-2312 encoding. How can I change the encoding from GB-2312 to UTF-8.
I tried this code
let enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000)
var result = NSString(data: data, encoding:enc)!
but it has an error
Use of unresolved identifier 'kCFStringEncodingGB_18030_2000'
I solved this issue with using the concrete value of gb312 constant instead of the apple defined constant
let enc = CFStringConvertEncodingToNSStringEncoding(0x0632);
let dogString:String = NSString(data: data, encoding: enc)!
println(dogString)
here is the better solution - and thanks for Daij-Djan's suggestion
let cfEnc = CFStringEncodings.GB_18030_2000
let enc = CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(cfEnc.rawValue))
let dogString:String = NSString(data: data, encoding: enc)!