Related
I tried to generate SHA256 in iOS using Arcane library with following data:
String: Amount=50&BillerID=59&ChannelID=2&Context=34|check|test&ReturnURL=https://uat.myfatoora.com/ReceiptPOC.aspx&TxnRefNum=000000000020003&UserName=DCS
Key: 71DD0F73AFFBB47825FF9864DDE95F3B
Result was 409dc622b3bef5c9fc46e45c3210111fcb4536d3a55833316fe0dc8154b3ea34
which I thought to be correct. However, the Windows counterpart is generating SHA256 using following code:
Windows Phone Source Code:
public static string HmacSha256(string secretKey, string value)
{
var msg = CryptographicBuffer.ConvertStringToBinary(value, BinaryStringEncoding.Utf8);
byte[] convertedHash = new byte[secretKey.Length / 2];
for (int i = 0; i < secretKey.Length / 2; i++)
{
convertedHash[i] = (byte)Int32.Parse(secretKey.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber);
}
// Create HMAC.
var objMacProv = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha256);
CryptographicHash hash = objMacProv.CreateHash(convertedHash.AsBuffer());
hash.Append(msg);
return CryptographicBuffer.EncodeToHexString(hash.GetValueAndReset());
}
and the result is: 94a20ca39c8487c7763823ec9c918d9e38ae83cb741439f6d129bcdef9edba73 which is different from what I got. Can somebody help me with this and let me know what the above code is doing and how can I replicate it in iOS.
Edit:
iOS Source code
let key = self.md5(string: "71DD0F73AFFBB47825FF9864DDE95F3B")
let hash = HMAC.SHA256(str, key: key)
The key here is you need to convert your secret, which is a hex string, into NSData. In other words, NSData byte stream would "look" like the secret.
This should do what you want:
// Hex string to NSData conversion from here http://stackoverflow.com/questions/7317860/converting-hex-nsstring-to-nsdata
NSString *secret = #"71DD0F73AFFBB47825FF9864DDE95F3B";
NSData *dataIn = [#"Amount=50&BillerID=59&ChannelID=2&Context=34|check|test&ReturnURL=https://uat.myfatoora.com/ReceiptPOC.aspx&TxnRefNum=000000000020003&UserName=DCS" dataUsingEncoding:NSUTF8StringEncoding];
NSMutableData *macOut = [NSMutableData dataWithLength:CC_SHA256_DIGEST_LENGTH];
secret = [secret stringByReplacingOccurrencesOfString:#" " withString:#""];
NSMutableData *secretData = [[NSMutableData alloc] init];
unsigned char whole_byte;
char byte_chars[3] = {'\0','\0','\0'};
int i;
for (i=0; i < [secret length]/2; i++) {
byte_chars[0] = [secret characterAtIndex:i*2];
byte_chars[1] = [secret characterAtIndex:i*2+1];
whole_byte = strtol(byte_chars, NULL, 16);
[secretData appendBytes:&whole_byte length:1];
}
CCHmac(kCCHmacAlgSHA256, secretData.bytes, secretData.length, dataIn.bytes, dataIn.length, macOut.mutableBytes);
NSMutableString *stringOut = [NSMutableString stringWithCapacity:macOut.length];
const unsigned char *macOutBytes = macOut.bytes;
for (NSInteger i=0; i<macOut.length; ++i) {
[stringOut appendFormat:#"%02x", macOutBytes[i]];
}
NSLog(#"dataIn: %#", dataIn);
NSLog(#"macOut: %#", macOut);
NSLog(#"stringOut: %#", stringOut);
Output:
2016-09-27 20:18:54.181 JKS[27562:5321334] dataIn: <416d6f75 6e743d35 30264269 6c6c6572 49443d35 39264368 616e6e65 6c49443d 3226436f 6e746578 743d3334 7c636865 636b7c74 65737426 52657475 726e5552 4c3d6874 7470733a 2f2f7561 742e6d79 6661746f 6f72612e 636f6d2f 52656365 69707450 4f432e61 73707826 54786e52 65664e75 6d3d3030 30303030 30303030 32303030 33265573 65724e61 6d653d44 4353>
2016-09-27 20:18:54.181 JKS[27562:5321334] macOut: <94a20ca3 9c8487c7 763823ec 9c918d9e 38ae83cb 741439f6 d129bcde f9edba73>
2016-09-27 20:18:54.181 JKS[27562:5321334] stringOut: 94a20ca39c8487c7763823ec9c918d9e38ae83cb741439f6d129bcdef9edba73
Updated with Swift (code should be cleaned up)
// http://stackoverflow.com/questions/29799361/generate-a-hmac-swift-sdk8-3-using-cchmac
func generateHMAC(key: String, data: String) -> String {
let keyData = key.dataFromHexadecimalString()! as NSData
let dataIn = data.data(using: .utf8)! as NSData
var result: [CUnsignedChar]
result = Array(repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), keyData.bytes, keyData.length, dataIn.bytes, dataIn.length, &result)
let hash = NSMutableString()
for val in result {
hash.appendFormat("%02hhx", val)
}
return hash as String
}
You can use this extension to convert the hex string to Data
// Modified slightly http://stackoverflow.com/questions/26501276/converting-hex-string-to-nsdata-in-swift
extension String {
func dataFromHexadecimalString() -> Data? {
var data = Data(capacity: characters.count / 2)
let regex = try! NSRegularExpression(pattern: "[0-9a-f]{1,2}", options: .caseInsensitive)
regex.enumerateMatches(in: self, options: [], range: NSMakeRange(0, characters.count)) { match, flags, stop in
let byteString = (self as NSString).substring(with: match!.range)
var num = UInt8(byteString, radix: 16)
data.append(&num!, count: 1)
}
return data
}
}
And to use do something like:
let secret = "71DD0F73AFFBB47825FF9864DDE95F3B"
let value = "Amount=50&BillerID=59&ChannelID=2&Context=34|check|test&ReturnURL=https://uat.myfatoora.com/ReceiptPOC.aspx&TxnRefNum=000000000020003&UserName=DCS"
print("\(generateHMAC(key: secret, data: value))")
Your output should be 94a20ca39c8487c7763823ec9c918d9e38ae83cb741439f6d129bcdef9edba73
You will need #import <CommonCrypto/CommonCrypto.h> in your bridging header.
The Windows code takes the string, interprets it as a hexadecimal number, and converts two characters a time into one byte.
Your Mac code most like takes the string as it is. Since the key starts with "71", your windows code takes that as a single byte with value 0x71 = 129, your Mac code takes it as two bytes with values '7' = 55 and '1' = 49.
All you need to do is convert the bytes on the Mac exactly as you do it on Windows. You might have to do the unthinkable and look at the source code of the Mac library to see how it does the actual hash calculation.
#import <CommonCrypto/CommonHMAC.h>
+ (NSString *)hmacSHA256EncryptString{
NSString * parameterSecret = #"input secret key";
NSString *plainString = #"input encrypt content string";
const char *secretKey = [parameterSecret cStringUsingEncoding:NSUTF8StringEncoding];
const char *plainData = [plainString cStringUsingEncoding:NSUTF8StringEncoding];
unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];
CCHmac(kCCHmacAlgSHA256, secretKey, strlen(secretKey), plainData, strlen(plainData), cHMAC);
NSData *HMACData = [NSData dataWithBytes:cHMAC length:sizeof(cHMAC)];
const unsigned char *bufferChar = (const unsigned char *)[HMACData bytes];
NSMutableString *hmacString = [NSMutableString stringWithCapacity:HMACData.length * 2];
for (int i = 0; i < HMACData.length; ++i){
[hmacString appendFormat:#"%02x", bufferChar[i]];
}
return hmacString;
}
I am following closely this document to authorize a hardware from my iOS app:
In iOS section, at step 5):
- (IBAction)onLogInButtonClicked:(id)sender {
NSArray *requestScopes = [NSArray arrayWithObjects:#"alexa:all", nil];
NSMutableDictionary *options = [[NSMutableDictionary alloc] init];
NSString* scopeData = [NSString stringWithFormat:#"{\"alexa:all\":{\"productID\":\"%#\","
"\"productInstanceAttributes\":{\"deviceSerialNumber\":\"%#\"}}}",
productId, deviceSerialNumber];
options[kAIOptionScopeData] = scopeData;
options[kAIOptionReturnAuthCode] = #YES;
options[kAIOptionCodeChallenge] = #"CODE_CHALLENGE_GOES_HERE";
options[kAIOptionCodeChallengeMethod] = #"S256";
[AIMobileLib authorizeUserForScopes:requestScopes delegate:delegate options:options];
}
what should productId in scopeData be? As I have read some other posts, it is said that productId is taken from ID column of an app created in AVS Developer Portal, which is not linked with the document as it mentions to App Console in Getting Started guide for iOS. So I am confused at how/where to take the productId.
deviceSerialNumber can be any unique string?
I implemented a code-challenge method in ObjC based on item 1) and 2) described in "Transferring an Authorization Code from a Mobile App to an Alexa-enabled Product" section. Is it correct? (since I have no reference example)
- (NSString *)codeChallenge {
verifier = [NSString randomStringWithLength:128]; // generate 128-char string containing [A-Z], [a-z], [0-9], "-", "_", ".", "~"
NSData *sha256 = [[verifier dataUsingEncoding:NSUTF8StringEncoding] SHA256]; // SHA256 that string
NSString *base64Enc = [sha256 base64EncodedStringWithOptions:0]; // base64 encode SHA256 result
NSLog(#"base64Enc: %#", base64Enc);
NSMutableString *ret = [NSMutableString string];
for (NSInteger i=0; i<base64Enc.length; i++) { // remove "="; replace "+" with "-"; replace "/" with "_" as referenced from: http://tools.ietf.org/html/draft-ietf-oauth-spop-10#appendix-A
unichar c = [base64Enc characterAtIndex:i];
if (c == '=') {
continue;
}
else if (c == '+') {
[ret appendString:#"-"];
}
else if (c == '/') {
[ret appendString:#"_"];
}
else {
[ret appendFormat:#"%C", c];
}
}
return ret;
}
Regards,
So, it turned out that the App ID is the productID. You should able able find yours on Developer Console under Application Type Info tab. Your code challenge seems fine to me, but I'm not sure why you'd want to strip off =+-_. And yeah, deviceSerailNumber could be anything unique, I'm assuming that it should also be unique per installation.
The following in the Swift example for the same,
#IBAction func loginWithAmazon() {
let scopes = ["alexa:all"];
let codeChallenge = sha256("CODE_CHALLENGE_GOES_HERE".dataUsingEncoding(NSUTF8StringEncoding)!).base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
var options: [String: AnyObject] = [:]
let scopeData = String(format: "{\"alexa:all\":{\"productID\":\"%#\",\"productInstanceAttributes\":{\"deviceSerialNumber\":\"%#\"}}}", "yourAppIDHere", "anyUniqueID")
options[kAIOptionScopeData] = scopeData;
options[kAIOptionReturnAuthCode] = true;
options[kAIOptionCodeChallenge] = codeChallenge;
options[kAIOptionCodeChallengeMethod] = "S256";
AIMobileLib.authorizeUserForScopes(scopes, delegate: self, options: options);
}
func requestDidSucceed(apiResult: APIResult!) {
accessToken = apiResult.result
print(apiResult.result)
}
func requestDidFail(errorResponse: APIError!) {
print(errorResponse.error)
}
=================================================
func sha256(data : NSData) -> NSData {
var hash = [UInt8](count: Int(CC_SHA256_DIGEST_LENGTH), repeatedValue: 0)
CC_SHA256(data.bytes, CC_LONG(data.length), &hash)
let res = NSData(bytes: hash, length: Int(CC_SHA256_DIGEST_LENGTH))
return res
}
I have used the following Objective C routines for years, to convert a NSData push token into a NSString (for use by a web side push service), and the inverse, to take a known NSString version of the token and recreate the NSData representation. Now, I find the need for the exact same capabilities, but in Swift.
The dataToHex Objective C code essentially uses printf formatting:
- (NSString *)dataToHex:(NSData *)data
{
NSMutableString *str = [NSMutableString stringWithCapacity:100];
const unsigned char *p = [data bytes];
NSUInteger len = [data length];
for(int i=0; i<len; ++i) {
[str appendFormat:#"%02.2X", p[i]];
}
return str;
}
The inverse translation is:
- (NSData *)hexToData:(NSString *)str
{
const char *ptr = [str cStringUsingEncoding:NSASCIIStringEncoding];
NSUInteger len = [str length]/2;
NSMutableData *data = [NSMutableData dataWithCapacity:len];
while(len--) {
char num[5] = (char[]){ '0', 'x', 0, 0, 0 };
num[2] = *ptr++;
num[3] = *ptr++;
uint8_t n = (uint8_t)strtol(num, NULL, 0);
[data appendBytes:&n length:1];
}
return data;
}
By "cleverly" overwriting a two byes in an ASCII array, the "0xXX" string is converted into a byte, which is then appended to the mutable data object.
Now that I'm coding in Swift, I need the same capabilities but have not found any posts with anything like the code above in Swift.
Converting from the NSData representation as supplied by iOS matches the Objective C code almost line for line:
func dataToHex(data: NSData) -> String
{
var str: String = String()
let p = UnsafePointer<UInt8>(data.bytes)
let len = data.length
for var i=0; i<len; ++i {
str += String(format: "%02.2X", p[i])
}
return str
}
However, given an NSString object, the conversion back to a NSData object is a bit harder. You might need to do this if you are testing in the Simulator, have a string token from a real device, and need it to say register with a service.
The first approach I took tried to replicate code I used before, by creating a string with character pairs, and calling strtol:
func hexToData0(str: NSString) -> NSData {
let len = str.length/2
var data = NSMutableData(capacity:len)!
var num: [Int8] = [ 0, 0, 0 ]
let ptr = str.cStringUsingEncoding(NSUTF8StringEncoding)
for var i=0; i<len; ++i {
num[0] = ptr[i*2+0]
num[1] = ptr[i*2+1]
var n = UInt8 ( strtol(&num, nil, 16) )
data.appendBytes(&n, length:1)
}
return data;
}
I just felt the strtol was a bit of a hack, so I did the same using NSScanner that about the same code size, while most likely less efficient:
func hexToData1(str: NSString) -> NSData {
var data = NSMutableData(capacity: str.length/2)!
for var i = 0; i<str.length; i+=2 {
let r = NSRange(location: i, length: 2)
let s = str.substringWithRange(r)
let sc = NSScanner(string: s)
var val: UInt32 = 0
let ret = sc.scanHexInt(&val)
if ret {
var b = UInt8(val)
data.appendBytes(&b, length: 1)
} else {
assert(false, "Yikes!")
}
}
return data
}
Then, it occurred to me that I could do it all in Swift, no Darwin or Foundation needed, at the expense of a few more lines of code:
// Swift 4
func hexToData(str: String) -> Data {
let len = str.count/2
var data = Data(capacity:len)
let ptr = str.cString(using: String.Encoding.utf8)!
for i in 0..<len {
var num: UInt8 = 0
var multi: UInt8 = 16;
for j in 0..<2 {
let c: UInt8 = UInt8(ptr[i*2+j])
var offset: UInt8 = 0
switch c {
case 48...57: // '0'-'9'
offset = 48
case 65...70: // 'A'-'F'
offset = 65 - 10 // 10 since 'A' is 10, not 0
case 97...102: // 'a'-'f'
offset = 97 - 10 // 10 since 'a' is 10, not 0
default:
assert(false)
}
num += (c - offset)*multi
multi = 1
}
data.append(num)
}
return data;
}
I'm using the final hexToData in my code.
I am implementing push notifications. I'd like to save my APNS Token as a String.
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)newDeviceToken
{
NSString *tokenString = [NSString stringWithUTF8String:[newDeviceToken bytes]]; //[[NSString alloc]initWithData:newDeviceToken encoding:NSUTF8StringEncoding];
NSLog(#"%#", tokenString);
NSLog(#"%#", newDeviceToken);
}
The first line of code prints null. the second prints the token. How can I get my newDeviceToken as an NSString?
If anyone is looking for a way to do this in Swift:
Swift 3 introduces the Data type, with value semantics. To convert the deviceToken to a String, you can do as follows:
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
print(token)
}
Old answer using NSData:
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
var tokenString = ""
for i in 0..<deviceToken.length {
tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
}
print("tokenString: \(tokenString)")
}
Someone Helped me with this.I am just passing along
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)devToken {
const unsigned *tokenBytes = [deviceToken bytes];
NSString *hexToken = [NSString stringWithFormat:#"%08x%08x%08x%08x%08x%08x%08x%08x",
ntohl(tokenBytes[0]), ntohl(tokenBytes[1]), ntohl(tokenBytes[2]),
ntohl(tokenBytes[3]), ntohl(tokenBytes[4]), ntohl(tokenBytes[5]),
ntohl(tokenBytes[6]), ntohl(tokenBytes[7])];
[[MyModel sharedModel] setApnsToken:hexToken];
}
You could use this
- (NSString *)stringWithDeviceToken:(NSData *)deviceToken {
const char *data = [deviceToken bytes];
NSMutableString *token = [NSMutableString string];
for (NSUInteger i = 0; i < [deviceToken length]; i++) {
[token appendFormat:#"%02.2hhX", data[i]];
}
return [token copy];
}
For those who want in Swift 3 and most easier method
func extractTokenFromData(deviceToken:Data) -> String {
let token = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
return token.uppercased();
}
Note - This will not work when compiling with the iOS 13 or later SDK
use this :
NSString * deviceTokenString = [[[[deviceToken description]
stringByReplacingOccurrencesOfString: #"<" withString: #""]
stringByReplacingOccurrencesOfString: #">" withString: #""]
stringByReplacingOccurrencesOfString: #" " withString: #""];
NSLog(#"The generated device token string is : %#",deviceTokenString);
Explanation of %02.2hhx in the high vote answer:
%: Introduces the x conversion specifier.
02: The minimum width of the converted value is 2. If the converted value has fewer bytes than the field width, it shall be padded with 0 on the left.
.2: Gives the minimum number of digits to appear for the x conversion specifier.
hh: Specifies that the x conversion specifier applies to a signed char or unsigned char argument (the argument will have been promoted according to the integer promotions, but its value shall be converted to signed char or unsigned char before printing).
x: The unsigned argument shall be converted to unsigned hexadecimal format in the style "dddd"; the letters "abcdef" are used. The precision specifies the minimum number of digits to appear; if the value being converted can be represented in fewer digits, it shall be expanded with leading zeros. The default precision is 1. The result of converting zero with an explicit precision of zero shall be no characters.
For more details, see the IEEE printf specification.
Based on the above explanation, I think it is better to change %02.2hhx to %02x or %.2x.
For Swift 5, the following methods are all feasible:
deviceToken.map({String(format: "%02x", $0)}).joined()
deviceToken.map({String(format: "%.2x", $0)}).joined()
deviceToken.reduce("", {$0 + String(format: "%02x", $1)})
deviceToken.reduce("", {$0 + String(format: "%.2x", $1)})
The test is as follows:
let deviceToken = (0..<32).reduce(Data(), {$0 + [$1]})
print(deviceToken.reduce("", {$0 + String(format: "%.2x", $1)}))
// Print content:
// 000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f
In iOS 13 the description will be in different format. Kindly use below code to fetch the device token.
- (NSString *)fetchDeviceToken:(NSData *)deviceToken {
NSUInteger len = deviceToken.length;
if (len == 0) {
return nil;
}
const unsigned char *buffer = deviceToken.bytes;
NSMutableString *hexString = [NSMutableString stringWithCapacity:(len * 2)];
for (int i = 0; i < len; ++i) {
[hexString appendFormat:#"%02x", buffer[i]];
}
return [hexString copy];
}
It's my solution and It works well in my app:
NSString* newToken = [[[NSString stringWithFormat:#"%#",deviceToken]
stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"<>"]] stringByReplacingOccurrencesOfString:#" " withString:#""];
convert NSData to NSString with stringWithFormat
trim the "<>"
remove the spaces
I think converting deviceToken to hex byte string has no sense. Why? You will send it to your backend, where it will be transformed back to bytes to be pushed to APNS. So, use NSData's method base64EncodedStringWithOptions, push it to server, and then use reverse base64decoded data :) That is so much easier :)
NSString *tokenString = [tokenData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
In iOS 13 description will break so use this
let deviceTokenString = deviceToken.map { String(format: "%02x", $0) }.joined()
For clarity, let’s break this down and explain each part:
The map method operates on each element of a sequence. Because Data is a sequence of bytes in Swift, the passed closure is evaluated for each byte in deviceToken.
The String(format:) initializer evaluates each byte in the data (represented by the anonymous parameter $0) using the %02x format specifier, to produce a zero-padded, 2-digit hexadecimal representation of the byte / 8-bit integer.
After collecting each byte representation created by the map method, joined() concatenates each element into a single string.
P.S don't use description gives different string in iOS 12 and iOS 13 and not safe as per future scope. Developers shouldn’t have relied on a specific format for an object’s description.
// iOS 12
(deviceToken as NSData).description // "<965b251c 6cb1926d e3cb366f dfb16ddd e6b9086a 8a3cac9e 5f857679 376eab7C>"
// iOS 13
(deviceToken as NSData).description // "{length = 32, bytes = 0x965b251c 6cb1926d e3cb366f dfb16ddd ... 5f857679 376eab7c }"
For more information read This.
2020
token as text...
let tat = deviceToken.map{ data in String(format: "%02.2hhx", data) }.joined()
or if you prefer
let tat2 = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
(result is the same)
This is a little bit shorter solution:
NSData *token = // ...
const uint64_t *tokenBytes = token.bytes;
NSString *hex = [NSString stringWithFormat:#"%016llx%016llx%016llx%016llx",
ntohll(tokenBytes[0]), ntohll(tokenBytes[1]),
ntohll(tokenBytes[2]), ntohll(tokenBytes[3])];
Functional Swift version
One liner:
let hexString = UnsafeBufferPointer<UInt8>(start: UnsafePointer(data.bytes),
count: data.length).map { String(format: "%02x", $0) }.joinWithSeparator("")
Here's in a reusable and self documenting extension form:
extension NSData {
func base16EncodedString(uppercase uppercase: Bool = false) -> String {
let buffer = UnsafeBufferPointer<UInt8>(start: UnsafePointer(self.bytes),
count: self.length)
let hexFormat = uppercase ? "X" : "x"
let formatString = "%02\(hexFormat)"
let bytesAsHexStrings = buffer.map {
String(format: formatString, $0)
}
return bytesAsHexStrings.joinWithSeparator("")
}
}
Alternatively, use reduce("", combine: +) instead of joinWithSeparator("") to be seen as a functional master by your peers.
Edit: I changed String($0, radix: 16) to String(format: "%02x", $0), because one digit numbers needed to having a padding zero
(I don't know yet how to mark a question as a duplicate of this other one, so I just posted my answer again)
Throwing my answer on the pile. Avoid using string parsing; It's not guaranteed by the docs that NSData.description will always work that way.
Swift 3 Implementation:
extension Data {
func hexString() -> String {
var bytesPointer: UnsafeBufferPointer<UInt8> = UnsafeBufferPointer(start: nil, count: 0)
self.withUnsafeBytes { (bytes) in
bytesPointer = UnsafeBufferPointer<UInt8>(start: UnsafePointer(bytes), count:self.count)
}
let hexBytes = bytesPointer.map { return String(format: "%02hhx", $0) }
return hexBytes.joined()
}
}
This will work for you,
NSUInteger dataLength = deviceToken.length;
const unsigned char *dataBuffer = (const unsigned char *)deviceToken.bytes;
NSMutableString *deviceTokenString = [NSMutableString stringWithCapacity:(dataLength * 2)];
for (int i = 0; i < dataLength; ++i) {
[deviceTokenString appendFormat:#"%02x", dataBuffer[i]];
}
NSLog(#"The generated device token string is : %#",deviceTokenString);
I've tried to test two different methods with format "%02.2hhx" and "%02x"
var i :Int = 0
var j: Int = 0
let e: Int = Int(1e4)
let time = NSDate.timeIntervalSinceReferenceDate
while i < e {
_ = deviceToken.map { String(format: "%02x", $0) }.joined()
i += 1
}
let time2 = NSDate.timeIntervalSinceReferenceDate
let delta = time2-time
print(delta)
let time3 = NSDate.timeIntervalSinceReferenceDate
while j < e {
_ = deviceToken.reduce("", {$0 + String(format: "%02x", $1)})
j += 1
}
let time4 = NSDate.timeIntervalSinceReferenceDate
let delta2 = time4-time3
print(delta2)
and the result is that the fastest is "%02x" at average 2.0 vs 2.6 for the reduced version:
deviceToken.reduce("", {$0 + String(format: "%02x", $1)})
Here's how you do it in Xamarin.iOS
public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
{
var tokenStringBase64 = deviceToken.GetBase64EncodedString(NSDataBase64EncodingOptions.None);
//now you can store it for later use in local storage
}
Using updateAccumulatingResult is more efficient than the various other approaches found here, so here's the Swiftiest way to stringify your Data bytes:
func application(_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let token = deviceToken.reduce(into: "") { $0 += String(format: "%.2x", $1) }
print(token)
}
For Swift :
var characterSet: NSCharacterSet = NSCharacterSet( charactersInString: "<>" )
var deviceTokenString: String = ( deviceToken.description as NSString )
.stringByTrimmingCharactersInSet( characterSet )
.stringByReplacingOccurrencesOfString( " ", withString: "" ) as String
println( deviceTokenString )
NSString *tokenString = [[newDeviceToken description] stringByReplacingOccurrencesOfString:#"[<> ]" withString:#"" options:NSRegularExpressionSearch range:NSMakeRange(0, [[newDeviceToken description] length])];
Swift:
let tokenString = deviceToken.description.stringByReplacingOccurrencesOfString("[ <>]", withString: "", options: .RegularExpressionSearch, range: nil)
What about one line solution?
Objective C
NSString *token = [[data.description componentsSeparatedByCharactersInSet:[[NSCharacterSet alphanumericCharacterSet]invertedSet]]componentsJoinedByString:#""];
Swift
let token = data.description.components(separatedBy: CharacterSet.alphanumerics.inverted).joined()
-(NSString *)deviceTokenWithData:(NSData *)data
{
NSString *deviceToken = [[data description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"<>"]];
deviceToken = [deviceToken stringByReplacingOccurrencesOfString:#" " withString:#""];
return deviceToken;
}
Swift
// make sure that we have token for the devie on the App
func application(application: UIApplication
, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
var tokenStr = deviceToken.description
tokenStr = tokenStr.stringByReplacingOccurrencesOfString("<", withString: "", options: [], range: nil)
tokenStr = tokenStr.stringByReplacingOccurrencesOfString(">", withString: "", options: [], range: nil)
tokenStr = tokenStr.stringByReplacingOccurrencesOfString(" ", withString: "", options: [], range: nil)
print("my token is: \(tokenStr)")
}
Use excellent category!
// .h file
#interface NSData (DeviceToken)
- (NSString *)stringDeviceToken;
#end
// .m file
#import "NSData+DeviceToken.h"
#implementation NSData (DeviceToken)
- (NSString *)stringDeviceToken {
const unsigned *deviceTokenBytes = [deviceToken bytes];
NSString *deviceToken = [NSString stringWithFormat:#"%08x%08x%08x%08x%08x%08x%08x%08x",
ntohl(deviceTokenBytes[0]), ntohl(deviceTokenBytes[1]), ntohl(deviceTokenBytes[2]),
ntohl(deviceTokenBytes[3]), ntohl(deviceTokenBytes[4]), ntohl(deviceTokenBytes[5]),
ntohl(deviceTokenBytes[6]), ntohl(deviceTokenBytes[7])];
return deviceToken;
}
#end
// AppDelegate.m
#import "NSData+DeviceToken.h"
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
NSString *token = deviceToken.stringDeviceToken;
}
Works fine!
Swift 3:
If any one is looking for a way to get device token in Swift 3. Use the below modified snippet.
let characterSet: CharacterSet = CharacterSet( charactersIn: "<>" )
let deviceTokenString: String = (deviceToken.description as NSString)
.trimmingCharacters(in: characterSet as CharacterSet)
.replacingOccurrences(of: " ", with: "")
.uppercased()
print(deviceTokenString)
var token: String = ""
for i in 0..<deviceToken.count {
token += String(format: "%02.2hhx", deviceToken[i] as CVarArg)
}
print(token)
The solution #kulss posted here, while lacking in elegance but having the virtue of simplicity no longer works in iOS 13, since description will work differently for NSData. You can still use debugDescription though.
NSString * deviceTokenString = [[[[deviceToken debugDescription]
stringByReplacingOccurrencesOfString: #"<" withString: #""]
stringByReplacingOccurrencesOfString: #">" withString: #""]
stringByReplacingOccurrencesOfString: #" " withString: #""];
Try this one unless the data is null-terminated.
NSString* newStr = [[NSString alloc] initWithData:newDeviceToken
encoding:NSUTF8StringEncoding];
NSString *tokenstring = [[NSString alloc] initWithData:token encoding:NSUTF8StringEncoding];
I have a NSString like this:
http://www.
but I want to transform it to:
http%3A%2F%2Fwww.
How can I do this?
To escape the characters you want is a little more work.
Example code
iOS7 and above:
NSString *unescaped = #"http://www";
NSString *escapedString = [unescaped stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
NSLog(#"escapedString: %#", escapedString);
NSLog output:
escapedString: http%3A%2F%2Fwww
The following are useful URL encoding character sets:
URLFragmentAllowedCharacterSet "#%<>[\]^`{|}
URLHostAllowedCharacterSet "#%/<>?#\^`{|}
URLPasswordAllowedCharacterSet "#%/:<>?#[\]^`{|}
URLPathAllowedCharacterSet "#%;<>?[\]^`{|}
URLQueryAllowedCharacterSet "#%<>[\]^`{|}
URLUserAllowedCharacterSet "#%/:<>?#[\]^`
Creating a characterset combining all of the above:
NSCharacterSet *URLCombinedCharacterSet = [[NSCharacterSet characterSetWithCharactersInString:#" \"#%/:<>?#[\\]^`{|}"] invertedSet];
Creating a Base64
In the case of Base64 characterset:
NSCharacterSet *URLBase64CharacterSet = [[NSCharacterSet characterSetWithCharactersInString:#"/+=\n"] invertedSet];
For Swift 3.0:
var escapedString = originalString.addingPercentEncoding(withAllowedCharacters:.urlHostAllowed)
For Swift 2.x:
var escapedString = originalString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet())
Note: stringByAddingPercentEncodingWithAllowedCharacters will also encode UTF-8 characters needing encoding.
Pre iOS7 use Core Foundation
Using Core Foundation With ARC:
NSString *escapedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
NULL,
(__bridge CFStringRef) unescaped,
NULL,
CFSTR("!*'();:#&=+$,/?%#[]\" "),
kCFStringEncodingUTF8));
Using Core Foundation Without ARC:
NSString *escapedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)unescaped,
NULL,
CFSTR("!*'();:#&=+$,/?%#[]\" "),
kCFStringEncodingUTF8);
Note: -stringByAddingPercentEscapesUsingEncoding will not produce the correct encoding, in this case it will not encode anything returning the same string.
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding encodes 14 characrters:
`#%^{}[]|\"<> plus the space character as percent escaped.
testString:
" `~!##$%^&*()_+-={}[]|\\:;\"'<,>.?/AZaz"
encodedString:
"%20%60~!#%23$%25%5E&*()_+-=%7B%7D%5B%5D%7C%5C:;%22'%3C,%3E.?/AZaz"
Note: consider if this set of characters meet your needs, if not change them as needed.
RFC 3986 characters requiring encoding (% added since it is the encoding prefix character):
"!#$&'()*+,/:;=?#[]%"
Some "unreserved characters" are additionally encoded:
"\n\r \"%-.<>\^_`{|}~"
It's called URL encoding. More here.
-(NSString *)urlEncodeUsingEncoding:(NSStringEncoding)encoding {
return (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
(CFStringRef)self,
NULL,
(CFStringRef)#"!*'\"();:#&=+$,/?%#[]% ",
CFStringConvertNSStringEncodingToEncoding(encoding));
}
This is not my solution. Someone else wrote in stackoverflow but I have forgotten how.
Somehow this solution works "well". It handles diacritic, chinese characters, and pretty much anything else.
- (NSString *) URLEncodedString {
NSMutableString * output = [NSMutableString string];
const char * source = [self UTF8String];
int sourceLen = strlen(source);
for (int i = 0; i < sourceLen; ++i) {
const unsigned char thisChar = (const unsigned char)source[i];
if (false && thisChar == ' '){
[output appendString:#"+"];
} else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' ||
(thisChar >= 'a' && thisChar <= 'z') ||
(thisChar >= 'A' && thisChar <= 'Z') ||
(thisChar >= '0' && thisChar <= '9')) {
[output appendFormat:#"%c", thisChar];
} else {
[output appendFormat:#"%%%02X", thisChar];
}
}
return output;
}
If someone would tell me who wrote this code, I'll really appreciate it. Basically he has some explanation why this encoded string will decode exactly as it wish.
I modified his solution a little. I like space to be represented with %20 rather than +. That's all.
NSString * encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(NUL,(CFStringRef)#"parameter",NULL,(CFStringRef)#"!*'();#&+$,/?%#[]~=_-.:",kCFStringEncodingUTF8 );
NSURL * url = [[NSURL alloc] initWithString:[#"address here" stringByAppendingFormat:#"?cid=%#",encodedString, nil]];
This can work in Objective C ARC.Use CFBridgingRelease to cast a Core Foundation-style object as an Objective-C object and transfer ownership of the object to ARC .See Function CFBridgingRelease here.
+ (NSString *)encodeUrlString:(NSString *)string {
return CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes
(kCFAllocatorDefault,
(__bridge CFStringRef)string,
NULL,
CFSTR("!*'();:#&=+$,/?%#[]"),
kCFStringEncodingUTF8)
);}
Swift iOS:
Just For Information : I have used this:
extension String {
func urlEncode() -> CFString {
return CFURLCreateStringByAddingPercentEscapes(
nil,
self,
nil,
"!*'();:#&=+$,/?%#[]",
CFStringBuiltInEncodings.UTF8.rawValue
)
}
}// end extension String
Here's what I use. Note you have to use the #autoreleasepool feature or the program might crash or lockup the IDE. I had to restart my IDE three times until I realized the fix. It appears that this code is ARC compliant.
This question has been asked many times, and many answers given, but sadly all of the ones selected (and a few others suggested) are wrong.
Here's the test string that I used: This is my 123+ test & test2. Got it?!
These are my Objective C++ class methods:
static NSString * urlDecode(NSString *stringToDecode) {
NSString *result = [stringToDecode stringByReplacingOccurrencesOfString:#"+" withString:#" "];
result = [result stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
return result;
}
static NSString * urlEncode(NSString *stringToEncode) {
#autoreleasepool {
NSString *result = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)stringToEncode,
NULL,
(CFStringRef)#"!*'\"();:#&=+$,/?%#[]% ",
kCFStringEncodingUTF8
));
result = [result stringByReplacingOccurrencesOfString:#"%20" withString:#"+"];
return result;
}
}
NSString *str = (NSString *)CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)yourString,
NULL,
CFSTR("/:"),
kCFStringEncodingUTF8);
You will need to release or autorelease str yourself.
Google implements this in their Google Toolbox for Mac. So that's a good place to peak how they're doing it. Another option is to include the Toolbox and use their implementation.
Checkout the implementation here. (Which comes down to exactly what people have been posting here).
This is how I am doing this in swift.
extension String {
func encodeURIComponent() -> String {
return self.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
}
func decodeURIComponent() -> String {
return self.componentsSeparatedByString("+").joinWithSeparator(" ").stringByRemovingPercentEncoding!
}
}
This is what I did on Swift 5:
func formatPassword() -> String {
var output = "";
for ch in self {
let char = String(ch)
switch ch {
case " ":
output.append("+")
break
case ".", "-", "_", "~", "a"..."z", "A"..."Z", "0"..."9":
output.append(char)
break
default:
print(ch)
let unicode = char.unicodeScalars.first?.value ?? 0
let unicodeValue = NSNumber(value: unicode).intValue
let hexValue = String(format: "%02X", arguments: [unicodeValue])
output = output.appendingFormat("%%%#", hexValue)
}
}
return output as String
}
Then I called this function where I defined my password.
//use NSString instance method like this:
+ (NSString *)encodeURIComponent:(NSString *)string
{
NSString *s = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
return s;
}
+ (NSString *)decodeURIComponent:(NSString *)string
{
NSString *s = [string stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
return s;
}
remember,you should only do encode or decode for your parameter value, not all the url you request.
int strLength = 0;
NSString *urlStr = #"http://www";
NSLog(#" urlStr : %#", urlStr );
NSMutableString *mutableUrlStr = [urlStr mutableCopy];
NSLog(#" mutableUrlStr : %#", mutableUrlStr );
strLength = [mutableUrlStr length];
[mutableUrlStr replaceOccurrencesOfString:#":" withString:#"%3A" options:NSCaseInsensitiveSearch range:NSMakeRange(0, strLength)];
NSLog(#" mutableUrlStr : %#", mutableUrlStr );
strLength = [mutableUrlStr length];
[mutableUrlStr replaceOccurrencesOfString:#"/" withString:#"%2F" options:NSCaseInsensitiveSearch range:NSMakeRange(0, strLength)];
NSLog(#" mutableUrlStr : %#", mutableUrlStr );