iphone SDK : How Can I Convert a string to SHA-1 A

2019-08-04 18:06发布

问题:

my convert code is all i have, but it converts a string to sha-1 to hex format. how can i convert sha-1 to base64 ?

-(NSString *)digest:(NSString*)input

    int i;

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

    uint8_t digest[CC_SHA1_DIGEST_LENGTH];

    CC_SHA1(data.bytes, data.length, digest);

    output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
                                                     length:CC_SHA1_DIGEST_LENGTH];

    for(i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
    {
        [output appendFormat:@"%02x", digest[i]];
    }
    return output;
}

回答1:

There's no built-in hashing or Base64 in iOS. You'll have to roll your own. Find a C implementation of SHA1 in Google; as for Base64, I've got one for you:

NSString *ToBase64(NSData *d)
{
    static const char ALPHABET[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    static const NSString *PAD1 = @"=", *PAD2 = @"==";  

    int l = [d length];
    unsigned char *p = (unsigned char*)[d bytes];
    unichar Chunk[4];
    NSMutableString *s = [NSMutableString stringWithCapacity:(l+3)*4/3];
    int i;
    int mod = l % 3;
    int ll = l - mod;
    unsigned int triad;
    NSString *sChunk;
    for(i=0;i<ll;i+=3)
    {
        triad = (p[i]<<16) | (p[i+1]<<8) | p[i+2];
        Chunk[0] = ALPHABET[(triad >> 18) & 0x3f];
        Chunk[1] = ALPHABET[(triad >> 12) & 0x3f];
        Chunk[2] = ALPHABET[(triad >> 6) & 0x3f];
        Chunk[3] = ALPHABET[triad & 0x3f];
        sChunk = [[NSString alloc] initWithCharacters:Chunk length:4];
        [s appendString:sChunk];
        [sChunk release];
    }
    if(mod == 1)
    {
        Chunk[0] = ALPHABET[(p[i] >> 2) & 0x3f];
        Chunk[1] = ALPHABET[(p[i] << 4) & 0x3f];
        sChunk = [[NSString alloc] initWithCharacters:Chunk length:2];
        [s appendString:sChunk];
        [sChunk release];
        [s appendString: PAD2];
    }
    if(mod == 2)
    {
        triad = (p[i]<<8) | p[i+1];
        Chunk[0] = ALPHABET[(triad >> 10) & 0x3f];
        Chunk[1] = ALPHABET[(triad >> 4) & 0x3f];
        Chunk[2] = ALPHABET[(triad << 2) & 0x3f];
        sChunk = [[NSString alloc] initWithCharacters:Chunk length:3];
        [s appendString:sChunk];
        [sChunk release];
        [s appendString: PAD1];     
    }
    return s;
}