gpt4 book ai didi

java - Objective C 等同于 Java 中的 MessageDigest?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:52:10 26 4
gpt4 key购买 nike

我正在执行将 Java 代码转换为 Objective C 的任务。

这是我必须转换的 Java 代码:

private String getHash(String input) 
{
String ret = null;
try
{
MessageDigest md = MessageDigest.getInstance("SHA-256");

byte[] bs = md.digest(input.getBytes("US-ASCII"));


StringBuffer sb = new StringBuffer();
for (byte b : bs)
{
String bt = Integer.toHexString(b & 0xff);
if(bt.length()==1)
{
sb.append("0");
}
sb.append(bt);
}
ret = sb.toString();
}
catch (Exception e)
{
}
return ret;
}

具体来说,我可以在与 MessageDigest class 具有相同功能的 Objective C 中使用什么? ?

最佳答案

像这样:

#import <CommonCrypto/CommonDigest.h>

+(NSString*) sha256:(NSString *)input
{
const char *s=[input cStringUsingEncoding:NSASCIIStringEncoding];
NSData *keyData=[NSData dataWithBytes:s length:strlen(s)];

uint8_t digest[CC_SHA256_DIGEST_LENGTH]={0};
CC_SHA256(keyData.bytes, 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;
}

关于java - Objective C 等同于 Java 中的 MessageDigest?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8668013/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com