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

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

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签名验证的代码:

  1. <?php
  2. function p1363_to_asn1(string $p1363): string {
  3. // P1363 format: r followed by s.
  4. // ASN.1 format: 0x30 b1 0x02 b2 r 0x02 b3 s.
  5. //
  6. // r and s must be prefixed with 0x00 if their first byte is > 0x7f.
  7. //
  8. // b1 = length of contents.
  9. // b2 = length of r after being prefixed if necessary.
  10. // b3 = length of s after being prefixed if necessary.
  11. $asn1 = ''; // ASN.1 contents.
  12. $len = 0; // Length of ASN.1 contents.
  13. $c_len = intdiv(strlen($p1363), 2); // Length of each P1363 component.
  14. // Separate P1363 signature into its two equally sized components.
  15. foreach (str_split($p1363, $c_len) as $c) {
  16. // 0x02 prefix before each component.
  17. $asn1 .= "\x02";
  18. if (unpack('C', $c)[1] > 0x7f) {
  19. // Add 0x00 because first byte of component > 0x7f.
  20. // Length of component = ($c_len + 1).
  21. $asn1 .= pack('C', $c_len + 1) . "\x00";
  22. $len += 2 + ($c_len + 1);
  23. } else {
  24. $asn1 .= pack('C', $c_len);
  25. $len += 2 + $c_len;
  26. }
  27. // Append formatted component to ASN.1 contents.
  28. $asn1 .= $c;
  29. }
  30. // 0x30 b1, then contents.
  31. return "\x30" . pack('C', $len) . $asn1;
  32. }
  33. $public_key_pem = "-----BEGIN PUBLIC KEY-----
  34. MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEJ4dnbrsp2Ee8HstJ3ubDDzJuf5E2+N7J
  35. H36jxJtX568mL7hGYo/U/ooUqtcZLd5pS6kLBFkLWeP58BlVxxru+n225WTp0PiI
  36. kJudSFwdmHR16+WTbxJSyOaQAoyM6xWA
  37. -----END PUBLIC KEY-----";
  38. $public_key = openssl_pkey_get_public($public_key_pem);
  39. $signature = "QfXwpqkDtL95mmcTA2BknDY32Ds6i+NdLPRqlbi2+niQOLgsSJMRVVALLQ7b50LQXRsRiPfiYi+m9WXAJxCE3aO20feTQWcVR1SP+LYXQUIZKqrijm3VW/GHtGMhjlqv";
  40. $nounce = "MPAeifrL7Z/dFPZcAukaTWxsZ+h4E7jtWsKzltx3YujjJuOOWw8dgzgKfm3a";
  41. $origin = "https://192.168.1.3:8441";
  42. $origin_digest = openssl_digest($origin, "sha384", true);
  43. $nounce_digest = openssl_digest($nounce, "sha384", true);
  44. $result = openssl_verify($origin_digest.$nounce_digest, p1363_to_asn1(base64_decode($signature)), $public_key, OPENSSL_ALGO_SHA384);
  45. if ($result == 1) {
  46. echo "signature is valid for given data.";
  47. } elseif ($result == 0) {
  48. echo "signature is invalid for given data.";
  49. } else {
  50. echo "Error: ".openssl_error_string();
  51. }

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

  1. package main
  2. import (
  3. "crypto/ecdsa"
  4. "crypto/sha512"
  5. "crypto/x509"
  6. "encoding/base64"
  7. "encoding/pem"
  8. "fmt"
  9. "math/big"
  10. )
  11. func main() {
  12. idCardPublicKey := []byte(LoadIDCardPublicPem())
  13. nonce := "MPAeifrL7Z/dFPZcAukaTWxsZ+h4E7jtWsKzltx3YujjJuOOWw8dgzgKfm3a"
  14. origin := "https://192.168.1.3:8441"
  15. webeidSig := "QfXwpqkDtL95mmcTA2BknDY32Ds6i+NdLPRqlbi2+niQOLgsSJMRVVALLQ7b50LQXRsRiPfiYi+m9WXAJxCE3aO20feTQWcVR1SP+LYXQUIZKqrijm3VW/GHtGMhjlqv"
  16. sigVerified := VerifySignature(idCardPublicKey, nonce, origin, webeidSig)
  17. fmt.Println("SIG VERIFIED: ", sigVerified)
  18. }
  19. func VerifySignature(publicKeyByte []byte, nounce string, origin string, signatureBase64 string) bool {
  20. block, _ := pem.Decode(publicKeyByte)
  21. parseResultPublicKey, err := x509.ParsePKIXPublicKey(block.Bytes)
  22. fmt.Println("PARSE ERR: ", err)
  23. publicKey := parseResultPublicKey.(*ecdsa.PublicKey)
  24. originHash := sha512.New384()
  25. _, err2 := originHash.Write([]byte(origin))
  26. if err2 != nil {
  27. panic(err2)
  28. }
  29. originHashSum := originHash.Sum(nil)
  30. nounceHash := sha512.New384()
  31. _, err2 = nounceHash.Write([]byte(nounce))
  32. if err2 != nil {
  33. panic(err2)
  34. }
  35. nounceHashSum := nounceHash.Sum(nil)
  36. originHashSum = append(originHashSum, nounceHashSum...)
  37. signature := []byte(Base64Decoding(signatureBase64))
  38. rByte, sByte := signature[:len(signature)/2], signature[len(signature)/2:]
  39. r := new(big.Int)
  40. r.SetBytes(rByte)
  41. s := new(big.Int)
  42. s.SetBytes(sByte)
  43. valid := ecdsa.Verify(publicKey, originHashSum[:], r, s)
  44. return valid
  45. }
  46. func LoadIDCardPublicPem() []byte {
  47. return []byte(`-----BEGIN PUBLIC KEY-----
  48. MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEJ4dnbrsp2Ee8HstJ3ubDDzJuf5E2+N7J
  49. H36jxJtX568mL7hGYo/U/ooUqtcZLd5pS6kLBFkLWeP58BlVxxru+n225WTp0PiI
  50. kJudSFwdmHR16+WTbxJSyOaQAoyM6xWA
  51. -----END PUBLIC KEY-----`)
  52. }
  53. func Base64Decoding(input string) []byte {
  54. data, err := base64.StdEncoding.DecodeString(input)
  55. if err != nil {
  56. return data
  57. }
  58. return data
  59. }

希望这可以帮助到您!

英文:

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:

  1. &lt;?php
  2. function p1363_to_asn1(string $p1363): string {
  3. // P1363 format: r followed by s.
  4. // ASN.1 format: 0x30 b1 0x02 b2 r 0x02 b3 s.
  5. //
  6. // r and s must be prefixed with 0x00 if their first byte is &gt; 0x7f.
  7. //
  8. // b1 = length of contents.
  9. // b2 = length of r after being prefixed if necessary.
  10. // b3 = length of s after being prefixed if necessary.
  11. $asn1 = &#39;&#39;; // ASN.1 contents.
  12. $len = 0; // Length of ASN.1 contents.
  13. $c_len = intdiv(strlen($p1363), 2); // Length of each P1363 component.
  14. // Separate P1363 signature into its two equally sized components.
  15. foreach (str_split($p1363, $c_len) as $c) {
  16. // 0x02 prefix before each component.
  17. $asn1 .= &quot;\x02&quot;;
  18. if (unpack(&#39;C&#39;, $c)[1] &gt; 0x7f) {
  19. // Add 0x00 because first byte of component &gt; 0x7f.
  20. // Length of component = ($c_len + 1).
  21. $asn1 .= pack(&#39;C&#39;, $c_len + 1) . &quot;\x00&quot;;
  22. $len += 2 + ($c_len + 1);
  23. } else {
  24. $asn1 .= pack(&#39;C&#39;, $c_len);
  25. $len += 2 + $c_len;
  26. }
  27. // Append formatted component to ASN.1 contents.
  28. $asn1 .= $c;
  29. }
  30. // 0x30 b1, then contents.
  31. return &quot;\x30&quot; . pack(&#39;C&#39;, $len) . $asn1;
  32. }
  33. $public_key_pem = &quot;-----BEGIN PUBLIC KEY-----
  34. MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEJ4dnbrsp2Ee8HstJ3ubDDzJuf5E2+N7J
  35. H36jxJtX568mL7hGYo/U/ooUqtcZLd5pS6kLBFkLWeP58BlVxxru+n225WTp0PiI
  36. kJudSFwdmHR16+WTbxJSyOaQAoyM6xWA
  37. -----END PUBLIC KEY-----&quot;;
  38. $public_key = openssl_pkey_get_public($public_key_pem);
  39. $signature = &quot;QfXwpqkDtL95mmcTA2BknDY32Ds6i+NdLPRqlbi2+niQOLgsSJMRVVALLQ7b50LQXRsRiPfiYi+m9WXAJxCE3aO20feTQWcVR1SP+LYXQUIZKqrijm3VW/GHtGMhjlqv&quot;;
  40. $nounce = &quot;MPAeifrL7Z/dFPZcAukaTWxsZ+h4E7jtWsKzltx3YujjJuOOWw8dgzgKfm3a&quot;;
  41. $origin = &quot;https://192.168.1.3:8441&quot;;
  42. $origin_digest = openssl_digest($origin, &quot;sha384&quot;, true);
  43. $nounce_digest = openssl_digest($nounce, &quot;sha384&quot;, true);
  44. $result = openssl_verify($origin_digest.$nounce_digest, p1363_to_asn1(base64_decode($signature)), $public_key, OPENSSL_ALGO_SHA384);
  45. if ($result == 1) {
  46. echo &quot;signature is valid for given data.&quot;;
  47. } elseif ($result == 0) {
  48. echo &quot;signature is invalid for given data.&quot;;
  49. } else {
  50. echo &quot;Error: &quot;.openssl_error_string();
  51. }

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

  1. package main
  2. import (
  3. &quot;crypto/ecdsa&quot;
  4. &quot;crypto/sha512&quot;
  5. &quot;crypto/x509&quot;
  6. &quot;encoding/base64&quot;
  7. &quot;encoding/pem&quot;
  8. &quot;fmt&quot;
  9. &quot;math/big&quot;
  10. )
  11. func main() {
  12. idCardPublicKey := []byte(LoadIDCardPublicPem())
  13. nonce := &quot;MPAeifrL7Z/dFPZcAukaTWxsZ+h4E7jtWsKzltx3YujjJuOOWw8dgzgKfm3a&quot;
  14. origin := &quot;https://192.168.1.3:8441&quot;
  15. webeidSig := &quot;QfXwpqkDtL95mmcTA2BknDY32Ds6i+NdLPRqlbi2+niQOLgsSJMRVVALLQ7b50LQXRsRiPfiYi+m9WXAJxCE3aO20feTQWcVR1SP+LYXQUIZKqrijm3VW/GHtGMhjlqv&quot;
  16. sigVerified := VerifySignature(idCardPublicKey, nonce, origin, webeidSig)
  17. fmt.Println(&quot;SIG VERIFIED: &quot;, sigVerified)
  18. }
  19. func VerifySignature(publicKeyByte []byte, nounce string, origin string, signatureBase64 string) bool {
  20. block, _ := pem.Decode(publicKeyByte)
  21. parseResultPublicKey, err := x509.ParsePKIXPublicKey(block.Bytes)
  22. fmt.Println(&quot;PARSE ERR: &quot;, err)
  23. publicKey := parseResultPublicKey.(*ecdsa.PublicKey)
  24. originHash := sha512.New384()
  25. _, err2 := originHash.Write([]byte(origin))
  26. if err2 != nil {
  27. panic(err2)
  28. }
  29. originHashSum := originHash.Sum(nil)
  30. nounceHash := sha512.New384()
  31. _, err2 = nounceHash.Write([]byte(nounce))
  32. if err2 != nil {
  33. panic(err2)
  34. }
  35. nounceHashSum := nounceHash.Sum(nil)
  36. originHashSum = append(originHashSum, nounceHashSum...)
  37. signature := []byte(Base64Decoding(signatureBase64))
  38. rByte, sByte := signature[:len(signature)/2], signature[len(signature)/2:]
  39. r := new(big.Int)
  40. r.SetBytes(rByte)
  41. s := new(big.Int)
  42. s.SetBytes(sByte)
  43. valid := ecdsa.Verify(publicKey, originHashSum[:], r, s)
  44. return valid
  45. }
  46. func LoadIDCardPublicPem() []byte {
  47. return []byte(`-----BEGIN PUBLIC KEY-----
  48. MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEJ4dnbrsp2Ee8HstJ3ubDDzJuf5E2+N7J
  49. H36jxJtX568mL7hGYo/U/ooUqtcZLd5pS6kLBFkLWeP58BlVxxru+n225WTp0PiI
  50. kJudSFwdmHR16+WTbxJSyOaQAoyM6xWA
  51. -----END PUBLIC KEY-----`)
  52. }
  53. func Base64Decoding(input string) []byte {
  54. data, err := base64.StdEncoding.DecodeString(input)
  55. if err != nil {
  56. return data
  57. }
  58. return data
  59. }

答案1

得分: 3

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

  1. ...
  2. originHashSum = append(originHashSum, nounceHashSum...)
  3. // 修复:显式哈希运算
  4. finalHash := sha512.New384()
  5. _, err2 = finalHash.Write([]byte(originHashSum))
  6. if err2 != nil {
  7. panic(err2)
  8. }
  9. finalHashSum := finalHash.Sum(nil)
  10. ...
  11. valid := ecdsa.Verify(publicKey, finalHashSum[:], r, s)
  12. ...
英文:

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

  1. ...
  2. originHashSum = append(originHashSum, nounceHashSum...)
  3. // Fix: Explicit hashing
  4. finalHash := sha512.New384()
  5. _, err2 = finalHash.Write([]byte(originHashSum))
  6. if err2 != nil {
  7. panic(err2)
  8. }
  9. finalHashSum := finalHash.Sum(nil)
  10. ...
  11. valid := ecdsa.Verify(publicKey, finalHashSum[:], r, s)
  12. ...

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:

确定