从raw r和s创建DER格式的ECDSA签名

Pau*_*bel 6 c openssl digital-signature

我有一个原始的ECDSA签名:R和S值.我需要一个DER编码版本的签名.有没有一种直接的方法在openssl中使用c接口执行此操作?

我目前的尝试是i2d_ECDSA_SIG(const ECDSA_SIG *sig, unsigned char **pp)用来填充一个ECDSA_SIG*.调用返回非零但目标缓冲区似乎没有更改.

我正在快速填写我的ECDSA_SIG rs价值观.我没有看到任何错误.手册页说我应该在拨打时分配r和sECDSA_SIG_new

ECDSA_SIG* ec_sig = ECDSA_SIG_new();

if (NULL == BN_bin2bn(sig, 32, (ec_sig->r))) {
  dumpOpenSslErrors();
 }
DBG("post r  :%s\n", BN_bn2hex(ec_sig->r));

if (NULL == BN_bin2bn(sig + 32, 32, (ec_sig->s))) {
  dumpOpenSslErrors();
 }
DBG("post s  :%s\n", BN_bn2hex(ec_sig->s));
Run Code Online (Sandbox Code Playgroud)

现在设置S和R:

post r :397116930C282D1FCB71166A2D06728120CF2EE5CF6CCD4E2D822E8E0AE24A30 post s :9E997D4718A7603942834FBDD22A4B856FC4083704EDE62033CF1A77CB9822A9

现在要制作编码签名.

int sig_size = i2d_ECDSA_SIG(ec_sig, NULL);
if (sig_size > 255) {
  DBG("signature is too large wants %d\n", sig_size);
 }
DBG("post i2d:%s\n", BN_bn2hex(ec_sig->s));
Run Code Online (Sandbox Code Playgroud)

s没变:

post i2d:9E997D4718A7603942834FBDD22A4B856FC4083704EDE62033CF1A77CB9822A9

此时我已准备好足够多的字节,并且我将目标设置为全部6s,因此很容易看到有哪些更改.

unsigned char* sig_bytes = new unsigned char[256];
memset(sig_bytes, 6, 256);

sig_size = i2d_ECDSA_SIG(ec_sig, (&sig_bytes));
DBG("New size %d\n", sig_size);
DBG("post i2d:%s\n", BN_bn2hex(ec_sig->s));

hexDump("Sig ", (const byte*)sig_bytes, sig_size);
Run Code Online (Sandbox Code Playgroud)

新的尺寸是71, New size 71并且s iis是相同的:

  `post i2d:9E997D4718A7603942834FBDD22A4B856FC4083704EDE62033CF1A77CB9822A9`
Run Code Online (Sandbox Code Playgroud)

十六进制转储全部是6s.

  --Sig --  
  0x06:   0x06:   0x06:   0x06:   0x06:   0x06:   0x06:   0x06: 
  0x06:   ...
Run Code Online (Sandbox Code Playgroud)

尽管调用没有返回0,转储仍然是6s.我缺少什么与DER编码这个原始签名?

dbu*_*ush 7

i2d_ECDSA_SIG修改它的第二个参数,增加签名的大小。来自 ecdsa.h:

/** DER encode content of ECDSA_SIG object (note: this function modifies *pp
 *  (*pp += length of the DER encoded signature)).
 *  \param  sig  pointer to the ECDSA_SIG object
 *  \param  pp   pointer to a unsigned char pointer for the output or NULL
 *  \return the length of the DER encoded ECDSA_SIG object or 0
 */
int   i2d_ECDSA_SIG(const ECDSA_SIG *sig, unsigned char **pp);
Run Code Online (Sandbox Code Playgroud)

因此,您需要跟踪sig_bytes调用时的原始值i2d_ECDSA_SIG

int sig_size = i2d_ECDSA_SIG(ec_sig, NULL);
unsigned char *sig_bytes = malloc(sig_size);
unsigned char *p;
memset(sig_bytes, 6, sig_size);

p = sig_bytes;
new_sig_size = i2d_ECDSA_SIG(_sig, &p);

// The value of p is now sig_bytes + sig_size, and the signature resides at sig_bytes
Run Code Online (Sandbox Code Playgroud)

输出:

30 45 02 20 39 71 16 93 0C 28 2D 1F CB 71 16 6A
2D 06 72 81 20 CF 2E E5 CF 6C CD 4E 2D 82 2E 8E
0A E2 4A 30 02 21 00 9E 99 7D 47 18 A7 60 39 42
83 4F BD D2 2A 4B 85 6F C4 08 37 04 ED E6 20 33
CF 1A 77 CB 98 22 A9
Run Code Online (Sandbox Code Playgroud)