在 Go 中使用 DSA 签署 SHA-256 哈希

sign a SHA-256 hash with DSA in Go

我想用 DSA 签署 SHA-256 散列。

使用Java我可以写:

 Signature sig = Signature.getInstance("SHA256withDSA");
 sig.initSign(priKey);
 sig.update(new byte[]{1});
 byte[] sign = sig.sign();
 System.out.println(HexUtil.encodeHexStr(sign));

使用Go语言,没找到解决方法

检查一个DSAWithSHA256签名的唯一实例在github.com/avast/apkverifier

    case x509.DSAWithSHA256:
        hash := sha256.Sum256(signed)
        pub := cert.PublicKey.(*dsa.PublicKey)
        reqLen := pub.Q.BitLen() / 8
        if reqLen > len(hash) {
            return fmt.Errorf("Digest algorithm is too short for given DSA parameters.")
        }
        digest := hash[:reqLen]

        dsaSig := new(dsaSignature)
        if rest, err := asn1.Unmarshal(signature, dsaSig); err != nil {
            return err
        } else if len(rest) != 0 {
            return errors.New("x509: trailing data after DSA signature")
        }
        if dsaSig.R.Sign() <= 0 || dsaSig.S.Sign() <= 0 {
            return errors.New("x509: DSA signature contained zero or negative values")
        }
        if !dsa.Verify(pub, digest, dsaSig.R, dsaSig.S) {
            return errors.New("x509: DSA verification failure")
        }

但实际上使用签名算法确实不受支持,原因如github.com/grantae/certinfo

Issues:

  1. Unfortunately, OpenSSL uses non-deterministic signing for DSA and ECDSA certificate requests, so running make-certs.sh will not reproduce the same CSRs despite having static keys.
    These files have to be kept in-sync manually.

  2. The x509 package does not currently set CertificateRequest.SignatureAlgorithm for DSA CSRs.
    Therefore the 'leaf2.csr.text' contains the line 'Signature Algorithm: 0' instead of 'Signature Algorithm: DSAWithSHA256' to allow the test to pass and indicate that the problem is with x509 and not this package.

因此它在 Go crypto/x509 包中 unsupported status