为什么在GO中验证ECDSA 384签名失败,但在PHP中却没有失败?

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

Why verification of ECDSA 384 signature fails in GO but not in PHP?

问题

我正在为您翻译以下内容:

我遇到了一个问题,需要验证由智能卡生成的签名。签名使用的是ECDSA 384算法,消息是两个字节数组(连接在一起),是SHA-384哈希字符串。我有一个用PHP编写的示例代码来执行签名验证,它按预期工作。然而,当我尝试在GO中复现相同类型的验证时,无论如何尝试,都无法验证签名。

我认为GO中原始消息哈希的某些地方出错了,它无法验证它,但我无法找出我做错了什么。也许有人可以指出实际原因是什么?我将在这里放置PHP和GO代码示例以及用于验证的示例数据:

这是用于PHP ECDSA 384签名验证的代码:

<?php

function p1363_to_asn1(string $p1363): string {
    // P1363 format: r followed by s.

    // ASN.1 format: 0x30 b1 0x02 b2 r 0x02 b3 s.
    //
    // r and s must be prefixed with 0x00 if their first byte is > 0x7f.
    //
    // b1 = length of contents.
    // b2 = length of r after being prefixed if necessary.
    // b3 = length of s after being prefixed if necessary.

    $asn1  = '';                        // ASN.1 contents.
    $len   = 0;                         // Length of ASN.1 contents.
    $c_len = intdiv(strlen($p1363), 2); // Length of each P1363 component.

    // Separate P1363 signature into its two equally sized components.
    foreach (str_split($p1363, $c_len) as $c) {
        // 0x02 prefix before each component.
        $asn1 .= "\x02";

        if (unpack('C', $c)[1] > 0x7f) {
            // Add 0x00 because first byte of component > 0x7f.
            // Length of component = ($c_len + 1).
            $asn1 .= pack('C', $c_len + 1) . "\x00";
            $len += 2 + ($c_len + 1);
        } else {
            $asn1 .= pack('C', $c_len);
            $len += 2 + $c_len;
        }

        // Append formatted component to ASN.1 contents.
        $asn1 .= $c;
    }

    // 0x30 b1, then contents.
    return "\x30" . pack('C', $len) . $asn1;
}

$public_key_pem = "-----BEGIN PUBLIC KEY-----
MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEJ4dnbrsp2Ee8HstJ3ubDDzJuf5E2+N7J
H36jxJtX568mL7hGYo/U/ooUqtcZLd5pS6kLBFkLWeP58BlVxxru+n225WTp0PiI
kJudSFwdmHR16+WTbxJSyOaQAoyM6xWA
-----END PUBLIC KEY-----";
$public_key = openssl_pkey_get_public($public_key_pem);

$signature = "QfXwpqkDtL95mmcTA2BknDY32Ds6i+NdLPRqlbi2+niQOLgsSJMRVVALLQ7b50LQXRsRiPfiYi+m9WXAJxCE3aO20feTQWcVR1SP+LYXQUIZKqrijm3VW/GHtGMhjlqv";
$nounce = "MPAeifrL7Z/dFPZcAukaTWxsZ+h4E7jtWsKzltx3YujjJuOOWw8dgzgKfm3a";
$origin = "https://192.168.1.3:8441";

$origin_digest = openssl_digest($origin, "sha384", true);
$nounce_digest = openssl_digest($nounce, "sha384", true);

$result = openssl_verify($origin_digest.$nounce_digest, p1363_to_asn1(base64_decode($signature)), $public_key, OPENSSL_ALGO_SHA384);

if ($result == 1) {
    echo "signature is valid for given data.";
} elseif ($result == 0) {
    echo "signature is invalid for given data.";
} else {
    echo "Error: ".openssl_error_string();
}

这是我在GO中使用的代码,尝试验证ECDSA 384签名:

package main

import (
	"crypto/ecdsa"
	"crypto/sha512"
	"crypto/x509"
	"encoding/base64"
	"encoding/pem"
	"fmt"
	"math/big"
)

func main() {

	idCardPublicKey := []byte(LoadIDCardPublicPem())
	nonce := "MPAeifrL7Z/dFPZcAukaTWxsZ+h4E7jtWsKzltx3YujjJuOOWw8dgzgKfm3a"
	origin := "https://192.168.1.3:8441"
	webeidSig := "QfXwpqkDtL95mmcTA2BknDY32Ds6i+NdLPRqlbi2+niQOLgsSJMRVVALLQ7b50LQXRsRiPfiYi+m9WXAJxCE3aO20feTQWcVR1SP+LYXQUIZKqrijm3VW/GHtGMhjlqv"
	sigVerified := VerifySignature(idCardPublicKey, nonce, origin, webeidSig)
	fmt.Println("SIG VERIFIED: ", sigVerified)

}

func VerifySignature(publicKeyByte []byte, nounce string, origin string, signatureBase64 string) bool {
	block, _ := pem.Decode(publicKeyByte)
	parseResultPublicKey, err := x509.ParsePKIXPublicKey(block.Bytes)
	fmt.Println("PARSE ERR: ", err)
	publicKey := parseResultPublicKey.(*ecdsa.PublicKey)

	originHash := sha512.New384()
	_, err2 := originHash.Write([]byte(origin))
	if err2 != nil {
		panic(err2)
	}
	originHashSum := originHash.Sum(nil)

	nounceHash := sha512.New384()
	_, err2 = nounceHash.Write([]byte(nounce))
	if err2 != nil {
		panic(err2)
	}
	nounceHashSum := nounceHash.Sum(nil)

	originHashSum = append(originHashSum, nounceHashSum...)

	signature := []byte(Base64Decoding(signatureBase64))
	rByte, sByte := signature[:len(signature)/2], signature[len(signature)/2:]
	r := new(big.Int)
	r.SetBytes(rByte)
	s := new(big.Int)
	s.SetBytes(sByte)

	valid := ecdsa.Verify(publicKey, originHashSum[:], r, s)
	return valid
}

func LoadIDCardPublicPem() []byte {
	return []byte(`-----BEGIN PUBLIC KEY-----
MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEJ4dnbrsp2Ee8HstJ3ubDDzJuf5E2+N7J
H36jxJtX568mL7hGYo/U/ooUqtcZLd5pS6kLBFkLWeP58BlVxxru+n225WTp0PiI
kJudSFwdmHR16+WTbxJSyOaQAoyM6xWA
-----END PUBLIC KEY-----`)
}

func Base64Decoding(input string) []byte {
	data, err := base64.StdEncoding.DecodeString(input)
	if err != nil {
		return data
	}
	return data
}

希望这可以帮助到您!

英文:

I am facing a issue where I have to verify a signature produced by a Smart Card. The signature is in ECDSA 384 and the message being used is two byte arrays (concatenated together) of SHA-384 hashed strings. I have a sample code written in PHP to perform the signature verification and it works as expected. However when I try to reproduce the same sort of verification in GO, I cannot get the signature verified no matter how I try it.

I believe that something is wrong with the original message hashing in GO that it does not verify it but I cannot figure out what I am doing wrong. Maybe someone can pin point out what the actual cause can be? I will put both PHP and GO code samples with sample data for verification here:

This is the code for PHP ECDSA 384 signature verification:

&lt;?php
function p1363_to_asn1(string $p1363): string {
// P1363 format: r followed by s.
// ASN.1 format: 0x30 b1 0x02 b2 r 0x02 b3 s.
//
// r and s must be prefixed with 0x00 if their first byte is &gt; 0x7f.
//
// b1 = length of contents.
// b2 = length of r after being prefixed if necessary.
// b3 = length of s after being prefixed if necessary.
$asn1  = &#39;&#39;;                        // ASN.1 contents.
$len   = 0;                         // Length of ASN.1 contents.
$c_len = intdiv(strlen($p1363), 2); // Length of each P1363 component.
// Separate P1363 signature into its two equally sized components.
foreach (str_split($p1363, $c_len) as $c) {
// 0x02 prefix before each component.
$asn1 .= &quot;\x02&quot;;
if (unpack(&#39;C&#39;, $c)[1] &gt; 0x7f) {
// Add 0x00 because first byte of component &gt; 0x7f.
// Length of component = ($c_len + 1).
$asn1 .= pack(&#39;C&#39;, $c_len + 1) . &quot;\x00&quot;;
$len += 2 + ($c_len + 1);
} else {
$asn1 .= pack(&#39;C&#39;, $c_len);
$len += 2 + $c_len;
}
// Append formatted component to ASN.1 contents.
$asn1 .= $c;
}
// 0x30 b1, then contents.
return &quot;\x30&quot; . pack(&#39;C&#39;, $len) . $asn1;
}
$public_key_pem = &quot;-----BEGIN PUBLIC KEY-----
MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEJ4dnbrsp2Ee8HstJ3ubDDzJuf5E2+N7J
H36jxJtX568mL7hGYo/U/ooUqtcZLd5pS6kLBFkLWeP58BlVxxru+n225WTp0PiI
kJudSFwdmHR16+WTbxJSyOaQAoyM6xWA
-----END PUBLIC KEY-----&quot;;
$public_key = openssl_pkey_get_public($public_key_pem);
$signature = &quot;QfXwpqkDtL95mmcTA2BknDY32Ds6i+NdLPRqlbi2+niQOLgsSJMRVVALLQ7b50LQXRsRiPfiYi+m9WXAJxCE3aO20feTQWcVR1SP+LYXQUIZKqrijm3VW/GHtGMhjlqv&quot;;
$nounce = &quot;MPAeifrL7Z/dFPZcAukaTWxsZ+h4E7jtWsKzltx3YujjJuOOWw8dgzgKfm3a&quot;;
$origin = &quot;https://192.168.1.3:8441&quot;;
$origin_digest = openssl_digest($origin, &quot;sha384&quot;, true);
$nounce_digest = openssl_digest($nounce, &quot;sha384&quot;, true);
$result = openssl_verify($origin_digest.$nounce_digest, p1363_to_asn1(base64_decode($signature)), $public_key, OPENSSL_ALGO_SHA384);
if ($result == 1) {
echo &quot;signature is valid for given data.&quot;;
} elseif ($result == 0) {
echo &quot;signature is invalid for given data.&quot;;
} else {
echo &quot;Error: &quot;.openssl_error_string();
}

Here is the code I used in GO to try to verify ECDSA 384 signature:

package main
import (
&quot;crypto/ecdsa&quot;
&quot;crypto/sha512&quot;
&quot;crypto/x509&quot;
&quot;encoding/base64&quot;
&quot;encoding/pem&quot;
&quot;fmt&quot;
&quot;math/big&quot;
)
func main() {
idCardPublicKey := []byte(LoadIDCardPublicPem())
nonce := &quot;MPAeifrL7Z/dFPZcAukaTWxsZ+h4E7jtWsKzltx3YujjJuOOWw8dgzgKfm3a&quot;
origin := &quot;https://192.168.1.3:8441&quot;
webeidSig := &quot;QfXwpqkDtL95mmcTA2BknDY32Ds6i+NdLPRqlbi2+niQOLgsSJMRVVALLQ7b50LQXRsRiPfiYi+m9WXAJxCE3aO20feTQWcVR1SP+LYXQUIZKqrijm3VW/GHtGMhjlqv&quot;
sigVerified := VerifySignature(idCardPublicKey, nonce, origin, webeidSig)
fmt.Println(&quot;SIG VERIFIED: &quot;, sigVerified)
}
func VerifySignature(publicKeyByte []byte, nounce string, origin string, signatureBase64 string) bool {
block, _ := pem.Decode(publicKeyByte)
parseResultPublicKey, err := x509.ParsePKIXPublicKey(block.Bytes)
fmt.Println(&quot;PARSE ERR: &quot;, err)
publicKey := parseResultPublicKey.(*ecdsa.PublicKey)
originHash := sha512.New384()
_, err2 := originHash.Write([]byte(origin))
if err2 != nil {
panic(err2)
}
originHashSum := originHash.Sum(nil)
nounceHash := sha512.New384()
_, err2 = nounceHash.Write([]byte(nounce))
if err2 != nil {
panic(err2)
}
nounceHashSum := nounceHash.Sum(nil)
originHashSum = append(originHashSum, nounceHashSum...)
signature := []byte(Base64Decoding(signatureBase64))
rByte, sByte := signature[:len(signature)/2], signature[len(signature)/2:]
r := new(big.Int)
r.SetBytes(rByte)
s := new(big.Int)
s.SetBytes(sByte)
valid := ecdsa.Verify(publicKey, originHashSum[:], r, s)
return valid
}
func LoadIDCardPublicPem() []byte {
return []byte(`-----BEGIN PUBLIC KEY-----
MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEJ4dnbrsp2Ee8HstJ3ubDDzJuf5E2+N7J
H36jxJtX568mL7hGYo/U/ooUqtcZLd5pS6kLBFkLWeP58BlVxxru+n225WTp0PiI
kJudSFwdmHR16+WTbxJSyOaQAoyM6xWA
-----END PUBLIC KEY-----`)
}
func Base64Decoding(input string) []byte {
data, err := base64.StdEncoding.DecodeString(input)
if err != nil {
return data
}
return data
}

答案1

得分: 3

openssl_verify() 隐式地进行哈希运算,而 ecdsa.Verify() 则不会。也就是说,在 Go 代码中缺少对 originHashSum 进行哈希运算的步骤:

...
originHashSum = append(originHashSum, nounceHashSum...)

// 修复:显式哈希运算
finalHash := sha512.New384()
_, err2 = finalHash.Write([]byte(originHashSum))
if err2 != nil {
	panic(err2)
}
finalHashSum := finalHash.Sum(nil)
	
...
	
valid := ecdsa.Verify(publicKey, finalHashSum[:], r, s)
...
英文:

openssl_verify() hashes implicitly, ecdsa.Verify() does not. I.e. in the Go code the hashing of originHashSum is missing:

...
originHashSum = append(originHashSum, nounceHashSum...)

// Fix: Explicit hashing
finalHash := sha512.New384()
_, err2 = finalHash.Write([]byte(originHashSum))
if err2 != nil {
	panic(err2)
}
finalHashSum := finalHash.Sum(nil)
	
...
	
valid := ecdsa.Verify(publicKey, finalHashSum[:], r, s)
...

huangapple
  • 本文由 发表于 2023年3月1日 19:28:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/75603088.html
匿名

发表评论

匿名网友

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

确定