使用Go生成SHA256withDSA签名,然后使用Java进行验证。

huangapple go评论164阅读模式
英文:

generate a SHA256withDSA signature using Go and then verify it using Java

问题

  1. 使用Go对原始数据进行SHA256哈希,然后进行DSA签名。
  2. 以十六进制打印签名结果。
  3. 使用Java的SHA256withDSA验证第一步的结果,返回false。
  4. 我知道SHA256和DSA是不同的,SHA256withDSA是另一种算法。
  5. 在Go中,如何生成一个可以使用Java的SHA256withDSA验证的签名?
  6. Go是否有其他第三方库支持?

请注意,我只会返回翻译好的部分,不会回答关于翻译的问题。

英文:
  1. Go sha256 orign data then DSA sign it
  2. print sign result by hex
  3. use Java SHA256withDSA to verify first step result return false
  4. i konw sha256 then DSA is difference SHA256withDSA
  5. how can i do in Go to generate a sign, that can be verified using sha256withdsa in Java ?
  6. do Go has any another third party library support ?

Go

package main

import (
	"crypto/dsa"
	"crypto/rand"
	"crypto/sha256"
	"encoding/asn1"
	"encoding/hex"
	"fmt"
	"golang.org/x/crypto/ssh"
	"math/big"
)

func main() {
	pemData := []byte("-----BEGIN DSA PRIVATE KEY-----\n" +
		"MIIBvAIBAAKBgQD9f1OBHXUSKVLfSpwu7OTn9hG3UjzvRADDHj+AtlEmaUVdQCJR\n" +
		"+1k9jVj6v8X1ujD2y5tVbNeBO4AdNG/yZmC3a5lQpaSfn+gEexAiwk+7qdf+t8Yb\n" +
		"+DtX58aophUPBPuD9tPFHsMCNVQTWhaRMvZ1864rYdcq7/IiAxmd0UgBxwIVAJdg\n" +
		"UI8VIwvMspK5gqLrhAvwWBz1AoGBAPfhoIXWmz3ey7yrXDa4V7l5lK+7+jrqgvlX\n" +
		"TAs9B4JnUVlXjrrUWU/mcQcQgYC0SRZxI+hMKBYTt88JMozIpuE8FnqLVHyNKOCj\n" +
		"rh4rs6Z1kW6jfwv6ITVi8ftiegEkO8yk8b6oUZCJqIPf4VrlnwaSi2ZegHtVJWQB\n" +
		"TDv+z0kqAoGBAIb9o0KPsjAdzjK571e1Mx7ZhEyJGrcxHiN2sW8IztEbqrKKiMxp\n" +
		"NlTwm234uBdtzVHE3uDWZpfHPMIRmwBjCYDFRowWWVRdhdFXZlpCyp1gMWqJ11dh\n" +
		"3FI3+O43DevRSyyuLRVCNQ1J3iVgwY5ndRpZU7n6y8DPH4/4EBT7KvnVAhR4Vwun\n" +
		"Fhu/+4AGaVeMEa814I3dqg==\n" +
		"-----END DSA PRIVATE KEY-----")

	p, _ := ssh.ParseRawPrivateKey(pemData)
	pp := p.(*dsa.PrivateKey)

	hashed := []byte{1}
	sha256 := sha256.New()
	sha256.Write(hashed)
	hashed = sha256.Sum(nil)
	r, s, _ := dsa.Sign(rand.Reader, pp, hashed)
	type dsaSignature struct {
		R, S *big.Int
	}
	var ss dsaSignature
	ss.S = s
	ss.R = r
	signatureBytes, _ := asn1.Marshal(ss)
	fmt.Println(hex.EncodeToString(signatureBytes))
}

Java

 @Test
    public void ttt() throws InvalidKeySpecException, NoSuchAlgorithmException, InvalidKeyException, SignatureException {
        String pubKey = "-----BEGIN PUBLIC KEY-----\n" +
                "MIIBuDCCASwGByqGSM44BAEwggEfAoGBAP1/U4EddRIpUt9KnC7s5Of2EbdSPO9E\n" +
                "AMMeP4C2USZpRV1AIlH7WT2NWPq/xfW6MPbLm1Vs14E7gB00b/JmYLdrmVClpJ+f\n" +
                "6AR7ECLCT7up1/63xhv4O1fnxqimFQ8E+4P208UewwI1VBNaFpEy9nXzrith1yrv\n" +
                "8iIDGZ3RSAHHAhUAl2BQjxUjC8yykrmCouuEC/BYHPUCgYEA9+GghdabPd7LvKtc\n" +
                "NrhXuXmUr7v6OuqC+VdMCz0HgmdRWVeOutRZT+ZxBxCBgLRJFnEj6EwoFhO3zwky\n" +
                "jMim4TwWeotUfI0o4KOuHiuzpnWRbqN/C/ohNWLx+2J6ASQ7zKTxvqhRkImog9/h\n" +
                "WuWfBpKLZl6Ae1UlZAFMO/7PSSoDgYUAAoGBAIb9o0KPsjAdzjK571e1Mx7ZhEyJ\n" +
                "GrcxHiN2sW8IztEbqrKKiMxpNlTwm234uBdtzVHE3uDWZpfHPMIRmwBjCYDFRowW\n" +
                "WVRdhdFXZlpCyp1gMWqJ11dh3FI3+O43DevRSyyuLRVCNQ1J3iVgwY5ndRpZU7n6\n" +
                "y8DPH4/4EBT7KvnV\n" +
                "-----END PUBLIC KEY-----";
        String publicKeyPEM = pubKey
                .replace("-----BEGIN PUBLIC KEY-----\n", "")
                .replaceAll(System.lineSeparator(), "")
                .replace("-----END PUBLIC KEY-----", "");
        byte[] publicEncoded = Base64.decodeBase64(publicKeyPEM);
        KeyFactory keyFactory1 = KeyFactory.getInstance("DSA");
        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicEncoded);
        DSAPublicKey pubKeyy = (DSAPublicKey) keyFactory1.generatePublic(publicKeySpec);

        Signature sig1 = Signature.getInstance("SHA256withDSA");
        sig1.initVerify(pubKeyy);
        byte[] orignData = new byte[]{1};
        sig1.update(orignData);
        boolean flag = sig1.verify(HexUtil.decodeHex("first step result"));
        System.out.println(flag);
    }

答案1

得分: 1

按照您的要求,以下是翻译好的代码部分:

遵循 FIPS186-4 的第4.6和4.7使用golang实现以下代码

hashed := []byte{1}
pemData, _ := ioutil.ReadFile("config/secure/private.key")
p, err := ssh.ParseRawPrivateKey(pemData)
pp, ok := p.(*dsa.PrivateKey)
h := sha256.New()
h.Write(hashed)
hashed := h.Sum(nil)
if pp.Q.BitLen()/8 < len(hashed) {
    hashed = hashed[0 : pp.Q.BitLen()/8]
}
r, s, _ := dsa.Sign(rand.Reader, pp, hashed)
var ss dsaSignature
ss.S = s
ss.R = r
hashed, _ = asn1.Marshal(ss)

请注意,我已经将代码中的&quot;替换为双引号",以便代码能够正确运行。

英文:

follow FIPS186-4 sections 4.6 and 4.7 golang should this

hashed := []byte{1}
pemData, _ := ioutil.ReadFile(&quot;config/secure/private.key&quot;)
p, err := ssh.ParseRawPrivateKey(pemData)
pp, ok := p.(*dsa.PrivateKey)
h := sha256.New()
h.Write(hashed)
hashed := h.Sum(nil)
if pp.Q.BitLen()/8 &lt; len(hashed) {
	hashed = hashed[0 : pp.Q.BitLen()/8]
}
r, s, _ := dsa.Sign(rand.Reader, pp, hashed)
var ss dsaSignature
ss.S = s
ss.R = r
hashed, _ = asn1.Marshal(ss)

答案2

得分: 0

我在Java中找到了以下代码:

package sun.security.provider;

private BigInteger generateS(BigInteger var1, BigInteger var2, BigInteger var3, BigInteger var4) throws SignatureException {
    byte[] var5;
    try {
        var5 = this.md.digest();
    } catch (RuntimeException var9) {
        throw new SignatureException(var9.getMessage());
    }

    // 这一行将哈希结果分割为256位
    int var6 = var2.bitLength() / 8;
    if (var6 < var5.length) {
        var5 = Arrays.copyOfRange(var5, 0, var6);
    }

    BigInteger var7 = new BigInteger(1, var5);
    BigInteger var8 = var4.modInverse(var2);
    return var1.multiply(var3).add(var7).multiply(var8).mod(var2);
}

你可以在Go中使用以下代码:

hashed := []byte{1}
sha256 := sha2562.New()
sha256.Write(hashed)
hashed = sha256.Sum(nil)
// 你必须将其分割
hashed = hashed[0:20]

原因是在Java中,SHA256结果被分割了,但在Go中没有被分割。

英文:

i found in java

package sun.security.provider;

private BigInteger generateS(BigInteger var1, BigInteger var2, BigInteger var3, BigInteger var4) throws SignatureException {
        byte[] var5;
        try {
            var5 = this.md.digest();
        } catch (RuntimeException var9) {
            throw new SignatureException(var9.getMessage());
        }

        // this line split the hash256 redsult
        int var6 = var2.bitLength() / 8;
        if (var6 &lt; var5.length) {
            var5 = Arrays.copyOfRange(var5, 0, var6);
        }

        BigInteger var7 = new BigInteger(1, var5);
        BigInteger var8 = var4.modInverse(var2);
        return var1.multiply(var3).add(var7).multiply(var8).mod(var2);
}

you can use in golang

	hashed := []byte{1}
	sha256 := sha2562.New()
	sha256.Write(hashed)
	hashed = sha256.Sum(nil)
    // you must split it 
	hashed = hashed[0:20]

the reason is sha256 result split in java , but glang not split

huangapple
  • 本文由 发表于 2021年9月2日 10:06:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/69023253.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定