2018.3.20
字符串
在線加密
在線加密1
iOS 簡單應(yīng)用
創(chuàng)建一個NSString分類
// NSString+RFCategory.h
#import <Foundation/Foundation.h>
@interface NSString (RFCategory)
///SHA-1加密
- (NSString *)rf_EncryptSHA1;
///SHA-256加密
- (NSString *)rf_EncryptSHA256;
///MD5加密
- (NSString *)rf_EncryptMD5;
@end
// NSString+RFCategory.m
#import "NSString+RFCategory.h"
#import <CommonCrypto/CommonDigest.h>
@implementation NSString (RFCategory)
- (NSString *)rf_EncryptSHA1 {
if (self.length<=0) return nil;
const char *cstr = [self cStringUsingEncoding:NSUTF8StringEncoding];
NSData *keyData = [NSData dataWithBytes:cstr length:self.length];
return [NSString RF_EncryptSHA1:keyData];
}
+ (NSString *)RF_EncryptSHA1:(NSData *)keyData {
if (keyData.length<=0) return nil;
uint8_t digest[CC_SHA1_DIGEST_LENGTH];
CC_SHA1(keyData.bytes, (unsigned int)keyData.length, digest);
NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
for (int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++) {
[output appendFormat:@"%02x", digest[i]];
}
return output;
}
- (NSString *)rf_EncryptSHA256 {
if (self.length<=0) return nil;
const char *s = [self cStringUsingEncoding:NSASCIIStringEncoding];
NSData *keyData = [NSData dataWithBytes:s length:strlen(s)];
return [NSString RF_EncryptSHA256:keyData];
}
+ (NSString *)RF_EncryptSHA256:(NSData *)keyData {
if (keyData.length<=0) return nil;
uint8_t digest[CC_SHA256_DIGEST_LENGTH] = {0};
CC_SHA256(keyData.bytes, (CC_LONG)keyData.length, digest);
NSData *out = [NSData dataWithBytes:digest length:CC_SHA256_DIGEST_LENGTH];
NSString *hash = [out description];
hash = [hash stringByReplacingOccurrencesOfString:@" " withString:@""];
hash = [hash stringByReplacingOccurrencesOfString:@"<" withString:@""];
hash = [hash stringByReplacingOccurrencesOfString:@">" withString:@""];
return hash;
}
- (NSString *)rf_EncryptMD5 {
if (self.length<=0) return nil;
const char *cStr = [self UTF8String];
unsigned char digest[16];
CC_MD5( cStr, (unsigned int)strlen(cStr), digest );
NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
[output appendFormat:@"%02x", digest[i]];
}
return output;
}
@end
參考鏈接:
1.iOS sha256加密