js和Object-c中sha1中文出错

来源:互联网 发布:dwg trueview for mac 编辑:程序博客网 时间:2024/06/15 16:21

js如何修改

由于js在内部编码上对中文是utf16于是在调用sha1方法前面加上转换字符

utf16转utf8

function utf16to8(str)  {
    var out, i, len, c;
 
    out = "";
    len = str.length;
    for(i = 0; i < len; i++){
        c = str.charCodeAt(i);
        if ((c >= 0x0001) && (c <= 0x007F)) {
            out += str.charAt(i);
        } else if (c > 0x07FF){
            out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
            out += String.fromCharCode(0x80 | ((c >>  6) & 0x3F));
            out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));
        } else {
            out += String.fromCharCode(0xC0 | ((c >>  6) & 0x1F));
            out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));
        }
    }
    return out;
}


Object-c如何修改

某第三方库代码

const char *cstr = [self cStringUsingEncoding:encoding];
NSData *data = [NSData dataWithBytes:cstr length:self.length];
uint8_t digest[CC_SHA1_DIGEST_LENGTH]; 
CC_SHA1(data.bytes, data.length, digest);  
NSMutableString* result = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];   
for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++) {
[result appendFormat:@"%02x", digest[i]];
}
return result.uppercaseString;

上面的方法中文字符串转data时会造成数据丢失,把

const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];  
NSData *data = [NSData dataWithBytes:cstr length:input.length]; 

这两句改成

NSData *data = [input dataUsingEncoding:NSUTF8StringEncoding];

就可以了

ps,这是因为我们遇到字符串先转成utf-8了,而后台遇到没转utf8,而是直接sha1加密。



0 0
原创粉丝点击