Go, DER和处理大整数

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

Go, DER and handling big integers

问题

我想创建一个Google Go应用程序,能够DER编码和解码大整数(即ECDSA签名r和s)。据我了解,我应该使用asn1包,但我应该调用哪些函数呢?

例如,我想要编码

316eb3cad8b66fcf1494a6e6f9542c3555addbf337f04b62bf4758483fdc881d

bf46d26cef45d998a2cb5d2d0b8342d70973fa7c3c37ae72234696524b2bc812

以获得以下结果:

30450220316eb3cad8b66fcf1494a6e6f9542c3555addbf337f04b62bf4758483fdc881d022100bf46d26cef45d998a2cb5d2d0b8342d70973fa7c3c37ae72234696524b2bc81201

反之亦然。我应该调用哪个函数进行编码,哪个函数进行解码,以及如何调用?

英文:

I want to create a Google Go application that will be able to DER encode and decode big integers (namely, ECDSA signature r and s). From what I understand I should use the asn1 package, but what functions should I be calling?

For example, I want to encode

316eb3cad8b66fcf1494a6e6f9542c3555addbf337f04b62bf4758483fdc881d

and

bf46d26cef45d998a2cb5d2d0b8342d70973fa7c3c37ae72234696524b2bc812

to get this:

30450220316eb3cad8b66fcf1494a6e6f9542c3555addbf337f04b62bf4758483fdc881d022100bf46d26cef45d998a2cb5d2d0b8342d70973fa7c3c37ae72234696524b2bc81201

and vice versa. Which function should I call for encoding, and which for decoding and how?

答案1

得分: 4

ECDSA-Sig-Value ::= SEQUENCE {
r INTEGER,
s INTEGER }

package main

import (
"fmt"
"big"
"asn1"
)

type ecdsa struct {
R, S *big.Int
}

func main() {
r, _ := new(big.Int).SetString("316eb3cad8b66fcf1494a6e6f9542c3555addbf337f04b62bf4758483fdc881d", 16);
s, _ := new(big.Int).SetString("bf46d26cef45d998a2cb5d2d0b8342d70973fa7c3c37ae72234696524b2bc812", 16);
sequence := ecdsa{r, s}
encoding, _ := asn1.Marshal(sequence)
fmt.Println(encoding)
dec := new(ecdsa)
asn1.Unmarshal(encoding, dec)
fmt.Println(dec)
}

英文:

You need to encode an ASN.1 sequence containing both r and s integers as follows:

ECDSA-Sig-Value ::= SEQUENCE {
  r INTEGER,
  s INTEGER }

Please note that I am not a Go developer but according to the documentation Marshal and Unmarshal functions seems to accept structs in order to encode/decode ASN.1 sequences.

This code sample seems to work for both encoding and decoding:

package main

import (
    "fmt"
    "big"
    "asn1"
)

type ecdsa struct {
    R, S *big.Int
}

func main() {
    r, _ := new(big.Int).SetString("316eb3cad8b66fcf1494a6e6f9542c3555addbf337f04b62bf4758483fdc881d", 16);
    s, _ := new(big.Int).SetString("bf46d26cef45d998a2cb5d2d0b8342d70973fa7c3c37ae72234696524b2bc812", 16);
    sequence := ecdsa{r, s}
    encoding, _ := asn1.Marshal(sequence)
    fmt.Println(encoding)
    dec := new(ecdsa)
    asn1.Unmarshal(encoding, dec)
    fmt.Println(dec)
}

huangapple
  • 本文由 发表于 2012年1月1日 22:17:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/8693513.html
匿名

发表评论

匿名网友

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

确定