【问题标题】:Sha256 in Objective-C for iPhoneiPhone 的 Objective-C 中的 Sha256
【发布时间】:2011-04-12 04:09:08
【问题描述】:

当我使用此代码创建字符串的 sha256 时

unsigned char hashedChars[32];
NSString *inputString;
inputString = [NSString stringWithFormat:@"hello"];
NSData * inputData = [inputString dataUsingEncoding:NSUTF8StringEncoding];
CC_SHA256(inputData.bytes, inputData.length, hashedChars);

它正确返回哈希,但我需要插入这样的字符串 \x00\x25\x53 并且在这种情况下,函数返回空字符串的 sha256,因为指定的编码不能用于转换接收器。

现在,我的问题是:如何插入这些特殊字符以生成正确的哈希?谢谢

【问题讨论】:

    标签: iphone objective-c xcode hash sha256


    【解决方案1】:

    试试这个,它对我有用

    1) 获取纯文本输入的哈希

    -(NSString*)sha256HashFor:(NSString*)input
    {   
        const char* str = [input UTF8String];
        unsigned char result[CC_SHA256_DIGEST_LENGTH];
        CC_SHA256(str, strlen(str), result);
    
        NSMutableString *ret = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH*2];
        for(int i = 0; i<CC_SHA256_DIGEST_LENGTH; i++)
        {
            [ret appendFormat:@"%02x",result[i]];
        }
        return ret;
    }
    

    2) 获取NSData 的哈希作为输入

    注意:-我用过NSData类,所以代码如下

        - (NSString *)SHA256_HASH {
        //if (!self) return nil;
    
        unsigned char hash[CC_SHA256_DIGEST_LENGTH];
        if ( CC_SHA256([(NSData*)self bytes], [(NSData*)self length], hash) ) {
            NSData *sha2 = [NSData dataWithBytes:hash length:CC_SHA256_DIGEST_LENGTH]; 
    
            // description converts to hex but puts <> around it and spaces every 4 bytes
            NSString *hash = [sha2 description];
            hash = [hash stringByReplacingOccurrencesOfString:@" " withString:@""];
            hash = [hash stringByReplacingOccurrencesOfString:@"<" withString:@""];
            hash = [hash stringByReplacingOccurrencesOfString:@">" withString:@""];
            // hash is now a string with just the 40char hash value in it
            //NSLog(@"hash = %@",hash);
    
            // Format SHA256 fingerprint like
            // 00:00:00:00:00:00:00:00:00
            int keyLength=[hash length];
            NSString *formattedKey = @"";
            for (int i=0; i<keyLength; i+=2) {
                NSString *substr=[hash substringWithRange:NSMakeRange(i, 2)];
                if (i!=keyLength-2) 
                    substr=[substr stringByAppendingString:@":"];
                formattedKey = [formattedKey stringByAppendingString:substr];
            }
    
            return formattedKey;
        }
        return nil;
    }
    

    【讨论】:

    • 如何为“Lähettäjä:”等特殊字符生成哈希??
    • 谢谢!第一个也使用特殊字符!
    • 稍微说明一下,if (!self) 是干什么用的?如果实例是nil,信号永远不会到达这个方法,对吧?
    • 什么是 CC_SHA256_DIGEST_LENGTH?知道了 - 需要#include &lt;CommonCrypto/CommonDigest.h&gt;
    • 如果您遇到隐式转换错误,您需要将行更改为 CC_SHA256(str, (CC_LONG)strlen(str), result);
    【解决方案2】:

    知道你需要导入是很重要的:

    #import <CommonCrypto/CommonDigest.h>
    

    希望对您有所帮助!

    【讨论】:

      【解决方案3】:

      那么您可能应该使用NSData 而不是NSString。你从哪里得到那个字符串?

      【讨论】:

      • 我的循环转换,例如“\x00\x25\x53”中的这个字符串“002553”,我会将此字节发送到 sha256 函数以创建哈希,但我显然有编码问题!
      【解决方案4】:

      有人在 Swift 3.0 中寻找解决方案。这里是

      extension String {
      
      // MARK: - SHA256
      func get_sha256_String() -> String {
          guard let data = self.data(using: .utf8) else {
              print("Data not available")
              return ""
          }
          return getHexString(fromData: digest(input: data as NSData))
      }
      
      private func digest(input : NSData) -> NSData {
          let digestLength = Int(CC_SHA256_DIGEST_LENGTH)
          var hashValue = [UInt8](repeating: 0, count: digestLength)
          CC_SHA256(input.bytes, UInt32(input.length), &hashValue)
          return NSData(bytes: hashValue, length: digestLength)
      }
      
      private  func getHexString(fromData data: NSData) -> String {
          var bytes = [UInt8](repeating: 0, count: data.length)
          data.getBytes(&bytes, length: data.length)
      
          var hexString = ""
          for byte in bytes {
              hexString += String(format:"%02x", UInt8(byte))
          }
          return hexString
      }}
      

      如何使用它

      let signatures = "yourStringToBeConverted".get_sha256_String()
      

      别忘了在你的 Bridging-Header.h

      中导入 #import &lt;CommonCrypto/CommonHMAC.h&gt;

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-09
        • 2011-05-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多