ECDSA 384签名在Go中验证失败但PHP正常的问题排查
ECDSA 384签名验证:PHP正常运行但Go无法通过的问题
需要验证智能卡生成的ECDSA 384签名,待验证消息为两个SHA-384哈希字符串的字节数组拼接结果。PHP签名验证代码可正常运行,但Go实现相同逻辑时始终无法通过验证,怀疑问题出在Go的消息哈希处理环节,以下是代码和测试数据:
PHP验证代码
<?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-----\nMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEJ4dnbrsp2Ee8HstJ3ubDDzJuf5E2+N7J\nH36jxJtX568mL7hGYo/U/ooUqtcZLd5pS6kLBFkLWeP58BlVxxru+n225WTp0PiI\nkJudSFwdmHR16+WTbxJSyOaQAoyM6xWA\n-----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验证代码(原错误版本)
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-----\nMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEJ4dnbrsp2Ee8HstJ3ubDDzJuf5E2+N7J\nH36jxJtX568mL7hGYo/U/ooUqtcZLd5pS6kLBFkLWeP58BlVxxru+n225WTp0PiI\nkJudSFwdmHR16+WTbxJSyOaQAoyM6xWA\n-----END PUBLIC KEY-----`) } func Base64Decoding(input string) []byte { data, err := base64.StdEncoding.DecodeString(input) if err != nil { return data } return data }
问题根源及修正方案
1. 公钥PEM格式错误
Go代码中LoadIDCardPublicPem返回的PEM字符串使用了\n字面量,但反引号包裹的字符串会将\n当作普通字符,导致PEM格式无效,公钥解析失败。需要将\n替换为实际换行符。
2. 哈希处理逻辑不一致
PHP的openssl_verify函数在指定OPENSSL_ALGO_SHA384时,会对传入的消息(两个哈希拼接的字节数组)再次计算SHA-384哈希,然后用这个最终哈希验证签名。而原Go代码直接将拼接后的哈希数组传给ecdsa.Verify,没有做二次哈希,导致验证的哈希值与PHP端不一致。
3. Base64解码错误处理不当
原Go代码中Base64Decoding函数在解码出错时仍返回错误数据,应该直接终止验证或返回false。
修正后的Go代码
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) if block == nil { fmt.Println("Failed to decode PEM") return false } parseResultPublicKey, err := x509.ParsePKIXPublicKey(block.Bytes) if err != nil { fmt.Println("PARSE ERR: ", err) return false } publicKey, ok := parseResultPublicKey.(*ecdsa.PublicKey) if !ok { fmt.Println("Not an ECDSA public key") return false } // 计算origin和nounce的SHA-384哈希 originHash := sha512.New384() _, err = originHash.Write([]byte(origin)) if err != nil { panic(err) } originHashSum := originHash.Sum(nil) nounceHash := sha512.New384() _, err = nounceHash.Write([]byte(nounce)) if err != nil { panic(err) } nounceHashSum := nounceHash.Sum(nil) // 拼接两个哈希 combined := append(originHashSum, nounceHashSum...) // 对拼接结果再次计算SHA-384,和PHP逻辑对齐 finalHash := sha512.New384() _, err = finalHash.Write(combined) if err != nil { panic(err) } finalHashSum := finalHash.Sum(nil) // Base64解码签名 signature, err := base64.StdEncoding.DecodeString(signatureBase64) if err != nil { fmt.Println("Base64 decode error: ", err) return false } // 拆分P1363格式的r和s if len(signature) != 96 { // ECDSA 384的P1363签名是384*2=768位=96字节 fmt.Println("Invalid signature length") return false } rByte, sByte := signature[:48], signature[48:] r := new(big.Int) r.SetBytes(rByte) s := new(big.Int) s.SetBytes(sByte) // 验证签名 valid := ecdsa.Verify(publicKey, finalHashSum, r, s) return valid } func LoadIDCardPublicPem() []byte { return []byte(`-----BEGIN PUBLIC KEY----- MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEJ4dnbrsp2Ee8HstJ3ubDDzJuf5E2+N7J H36jxJtX568mL7hGYo/U/ooUqtcZLd5pS6kLBFkLWeP58BlVxxru+n225WTp0PiI kJudSFwdmHR16+WTbxJSyOaQAoyM6xWA -----END PUBLIC KEY-----`) }
内容的提问来源于stack exchange,提问作者shadyee
相关产品推荐
相关产品推荐

