4

从 Java 框架管理 openssl 证书时遇到问题。

openssl x509 -subject_hash ...

输出不同于 Java 框架在调用时返回的输出X509_NAME_hash(),见下文。

原因是 openssl 改变了它计算 SHA1 的方式。现在,它不像 MD5 那样基于主题的 ASN.1 DER 表示中的散列,而是首先计算 CANONICAL 表示,然后在此基础上计算 ASN.1 DER,然后将其用作SHA1 算法的输入。

NativeCrypto.java

// --- X509_NAME -----------------------------------------------------------
public static int X509_NAME_hash(X500Principal principal) {
    return X509_NAME_hash(principal, "SHA1");
}

private static int X509_NAME_hash(X500Principal principal, String algorithm) {
    try {
        byte[] digest = MessageDigest.getInstance(algorithm).digest(principal.getEncoded());
        return Memory.peekInt(digest, 0, ByteOrder.LITTLE_ENDIAN);
    } catch (NoSuchAlgorithmException e) {
        throw new AssertionError(e);
    }
}

我一直在研究x_name.copensslx509_cmp.c库,试图在 Java 底层修复它。但我没有成功。

我知道我必须修改X509_NAME_hash. x509_cmp.c但不确定该更改是否应该在此之前或之后i2d_X509_NAME(x,NULL); 此方法正在计算主题名称的 CANONICAL 表示,对吗?那么,我需要根据该输出计算 ASN1 DER,对吗?但我就是做不到。

如果有人可以指导我或对此有所了解以解决此问题,我将不胜感激。

x509_cmp.c

    unsigned long X509_NAME_hash(X509_NAME *x)
    {
    unsigned long ret=0;
    unsigned char md[SHA_DIGEST_LENGTH];

    /* Make sure X509_NAME structure contains valid cached encoding */
    i2d_X509_NAME(x,NULL);
    if (!EVP_Digest(x->canon_enc, x->canon_enclen, md, NULL, EVP_sha1(),
            NULL))
            return 0;

    ret=(   ((unsigned long)md[0]     )|((unsigned long)md[1]<<8L)|
            ((unsigned long)md[2]<<16L)|((unsigned long)md[3]<<24L)
            )&0xffffffffL;
    return(ret);
    }

该函数x509_name_canon显然执行重新编码。这是在crypto/asn1/x_name.c

/* This function generates the canonical encoding of the Name structure.
 * In it all strings are converted to UTF8, leading, trailing and
 * multiple spaces collapsed, converted to lower case and the leading
 * SEQUENCE header removed.
 * 
 */
4

1 回答 1

1

您离它不是很远,如果您想要与 OpenSSL new SubjectHash 相同的结果,您必须删除 DN 的前导序列。因此,您必须执行以下操作:

// --- X509_NAME -----------------------------------------------------------

public static int X509_NAME_hash(X500Principal principal) {
    return X509_NAME_hash(principal, "SHA1");
}

private static int X509_NAME_hash(X500Principal principal, String algorithm) {
    try {

        byte[] princ = principal.getEncoded();
        final ASN1Sequence obj = (ASN1Sequence) ASN1Object.fromByteArray( princ );

        // Remove the leading sequence ...
        final DERSet enc = (DERSet) obj.getObjectAt(0);
        final byte[] toHash = enc.getDEREncoded();

        MessageDigest md = MessageDigest.getInstance(algorithm);
        byte[] digest = md.digest(toHash);
        return Memory.peekInt(digest, 0, ByteOrder.LITTLE_ENDIAN);

    } catch (NoSuchAlgorithmException e) {
        throw new AssertionError(e);
    } catch (IOException e) {
        throw new AssertionError(e);
    }
}

结果与 OpenSSL new Subject_hash 相同。

于 2013-11-14T07:42:53.327 回答