在項目中,Android系統先完成開發,所以IOS系統就參照Android的完成。在密碼加密環節,就必須要保持一致了。
Android代碼
public class Crypto {
/**
* Define a hash type enumeration for strong-typing
*/
public enum HashType {
MD5("MD5"), SHA1("SHA-1"), SHA256("SHA-256"), SHA512("SHA-512");
private String algorithm;
HashType(String algorithm) {
this.algorithm = algorithm;
}
@Override
public String toString() {
return this.algorithm;
}
}
/**
* Set-up MD5 as the default hashing algorithm
*/
private static final HashType DEFAULT_HASH_TYPE = HashType.SHA256;
/**
* Create a password hash using the default hashing algorithm
*
* @param input
* The password
* @return The password hash
*/
public static String passwordHash(String input) {
return passwordHash(input, DEFAULT_HASH_TYPE);
}
public static String passwordHash(String input, HashType hashType) {
try {
MessageDigest m = MessageDigest.getInstance(hashType.toString());
byte[] out = m.digest(input.getBytes());
return new String(Base64.encodeBase64(out));
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
}
IOS方法
+ (NSString*) sha256:(NSString *)stringpass
{
const char *cstr = [stringpass UTF8String];
NSData *data = [NSData dataWithBytes:cstr length:stringpass.length];
uint8_t digest[CC_SHA256_DIGEST_LENGTH];
CC_SHA256(data.bytes,data.length, digest);
NSData *da=[[NSData alloc]initWithBytes:digest length:CC_SHA256_DIGEST_LENGTH];
NSData *str=[GTMBase64 encodeData:da];
NSString *output=[[NSString alloc]initWithData:str encoding:NSUTF8StringEncoding];
return output;
}