验证SSL打开SHA1哈希在Java中

问题描述:

在我们的项目中,我们使用以下的OpenSSL函数创建一个SHA1哈希值,验证SSL打开SHA1哈希在Java中

SHA_CTX ctx; 
SHA1_Init (&ctx); 
SHA1_Update (&ctx, value, size); 
SHA1_Final (returned_hash, &ctx); 

我们使用一个密钥和SHA1_Update被多次调用。

我必须验证使用Java的散列。我已经写了以下的功能,

public static Mac hmacSha1Init(String key) { 
     Mac mac = null; 
     try { 
      // Get an hmac_sha1 key from the raw key bytes 
      byte[] keyBytes = key.getBytes(); 
      SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1"); 

      // Get an hmac_sha1 Mac instance and initialize with the signing key 
      mac = Mac.getInstance("HmacSHA1"); 
      mac.init(signingKey); 
     } catch (Exception e) { 
      throw new RuntimeException(e); 
     } 
     return mac; 
    } 

    public static Mac hmacSha1Update(String value, Mac mac) { 
     try { 
      // update hmac with value 
      mac.update(value.getBytes()); 
     } catch (Exception e) { 
      throw new RuntimeException(e); 
     } 
     return mac; 
    } 

    public static String hmacSha1Final(Mac mac) { 
     try { 
      // Compute the hmac on input data bytes 
      byte[] rawHmac = mac.doFinal(); 
      return Base64.encodeBase64String(rawHmac); 


     } catch (Exception e) { 
      throw new RuntimeException(e); 
     } 
    } 

我使用与Mac的钥匙和更新多次hmacSha1Init最后调用hmacSha1Final与MAC。

Ex。

Mac mac = hmacSha1Init("ssdsdsdioj298932276302392pdsdsfsdfs"); 


mac = hmacSha1Update("value1", mac); 
mac = hmacSha1Update("value2", mac); 
mac = hmacSha1Update("value3"', mac); 
String hash = hmacSha1Final(mac); 

但我没有得到通过OpenSSL生成相同的SHA1哈希。网络上的文档非常有限。有人可以指导我

+0

第一个问题 - 不使用参数的'的getBytes()'方法。在这种情况下可能不是问题,但使用系统默认编码IMO是一个非常糟糕的主意。 –

+0

@JonSkeet谢谢乔恩,我改变了我的代码(不是在qn中),但是你怀疑事实并非如此。但是,谢谢 – Ish

+0

您能否提供您的实际产量和预期产量的详细信息?我有*猜测*,但它可能是错误的... –

两个哈希值不同的原因是openssl SHA1算法中使用的输入与Java框架中使用的输入不同。 如果您使用MD5算法,您会看到结果相同。在这种情况下,openssl使用相同的。

有什么变化?好吧,openssl认为SHA1不够安全,没问题,所以他们决定给它一个回合。通常(MD5和Java框架),输入字符串并生成一个ASN1 DER编码。然后他们把它传递给算法。对于SHA1,openssl在生成ASN1 DER编码之前进行规范化处理。它正在计算输入的CANONICAL格式,然后生成ASN1 DER,然后将其传递给算法。您将不得不修改Java框架以获得相同的结果。我试图做我自己太:)

在这里你可以找到关于它的OpenSSL的通讯组列表后:http://openssl.6102.n7.nabble.com/The-new-subject-hash-algorithm-td44844.html

而且这里距离ICM Uniwersytet Warszawski的实现。不知道它有多可靠,这就是为什么我在尝试自己。

https://github.com/eu-emi/canl-java/blob/master/src/main/java/eu/emi/security/authn/x509/helpers/trust/OpensslTruststoreHelper.java