简体   繁体   English

如何为java.security.Signature签名方法指定签名长度

[英]how to specify signature length for java.security.Signature sign method

For my application, I'm trying to sign some byte contents using java.security.Signature class. 对于我的应用程序,我试图使用java.security.Signature类对一些字节内容进行签名。 The problem I'm having is that signature is never generated at a fixed length. 我遇到的问题是签名永远不会以固定的长度生成。 For instance, sometimes it is generated at a length of 135, 136 or 137 bytes. 例如,有时会以135、136或137个字节的长度生成它。 Is there a way to specify the length or some padding at the end? 有没有一种方法可以指定长度或在末尾添加一些填充? Any other ideas or comments are appreciated. 任何其他想法或意见,表示赞赏。

    private byte[] ecdsaSign(ECPrivateKey key, byte[] content) throws Exception {
                Signature ecdsaSign = Signature.getInstance("SHA256withECDSA", "SC");
                ecdsaSign.initSign(key);
                ecdsaSign.update(content);
                byte[] signature = ecdsaSign.sign();
                return signature;
}

For ECDSA Java crypto uses the ASN.1 DER encoding standardized by X9.62, SEC1 and rfc 3279 sec 2.2.3 , which varies slightly in length . 对于ECDSA, Java加密使用由X9.62,SEC1和rfc 3279 sec 2.2.3标准化的ASN.1 DER编码 ,其长度略有不同 This is covered in more detail on another Stack: https://crypto.stackexchange.com/questions/1795/how-can-i-convert-a-der-ecdsa-signature-to-ASN.1 and https://crypto.stackexchange.com/questions/33095/shouldnt-a-signature-using-ecdsa-be-exactly-96-bytes-not-102-or-103 and https://crypto.stackexchange.com/questions/37528/why-do-openssl-elliptic-curve-digital-signatures-differ-by-one-byte 这在另一个堆栈上有更详细的介绍: https: //crypto.stackexchange.com/questions/1795/how-can-i-convert-a-der-ecdsa-signature-to-ASN.1https:// crypto.stackexchange.com/questions/33095/shouldnt-a-signature-using-ecdsa-be-exactly-96-bytes-not-102-or-103https://crypto.stackexchange.com/questions/37528/为什么openssl椭圆曲线数字签名相差一个字节

This is also true for DSA, but not RSA, where signatures (and cryptograms since RSA supports both signature and encryption) are fixed length for a given key, as defined by I2OS and OS2I in PKCS1. 对于DSA来说也是如此,但对于RSA则不然,在RSA中,签名(以及密码,因为RSA支持签名和加密)是给定密钥的固定长度,如PKCS1中的I2OS和OS2I所定义。

If you want a different encoding, such as the fixed-length one used by PKCS11 (and your provider name "SC" suggests that possibility), you must convert it. 如果您要使用其他编码,例如PKCS11使用的固定长度编码(并且提供程序名称“ SC”表明存在这种可能性),则必须进行转换。

Added 2019-10: you no longer have to do it yourself in Java; 2019-10新增:您不再需要用Java自己做; BouncyCastle since 1.61 (2019-02) correctly supports this, as does SunEC in Java 9 up (2018-12). 从1.61(2019-02)开始的BouncyCastle 正确地支持此功能,Java 9 up(2018-12)中的SunEC也是如此。 See later near-dupe Java ECDSAwithSHA256 signature with inconsistent length . 请参见稍后的长度不一致的近重复Java ECDSAwithSHA256签名

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM