Giter VIP home page Giter VIP logo

gmsm's People

Contributors

dependabot[bot] avatar emmansun avatar opensvn avatar trisia avatar xuyang2 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

gmsm's Issues

[sync] crypto/x509: omit empty extensions SEQUENCE

In CreateCertificate, if there are no extensions, don't include the
extensions SEQUENCE in the encoded certificate.

Why, you might ask, does the encoding/asn1 tag 'optional' not do
the same thing as 'omitempty'? Good question, no clue, fixing that
would probably break things in horrific ways.

SM9 ARM64 test fail

=== RUN Test_gfp12Gen
bn_pair_test.go:56: not expected
--- FAIL: Test_gfp12Gen (0.01s)
=== RUN Test_Pairing_A2
bn_pair_test.go:66: not expected
--- FAIL: Test_Pairing_A2 (0.01s)
=== RUN Test_Pairing_B2
bn_pair_test.go:87: not expected
--- FAIL: Test_Pairing_B2 (0.01s)
=== RUN Test_Pairing_B2_2
bn_pair_test.go:101: not expected
--- FAIL: Test_Pairing_B2_2 (0.01s)
=== RUN Test_finalExponentiation
bn_pair_test.go:146: got (((4b5a0f5ff90fa92c62bfc03966907d70a5ab6b3dc19a6a8865593e43a82d258d, aa07bd07b8f029b3a1fd94a34e97fc650fefeb42ad86a5ec1979ff24bc1a1b11), (11554e7dee75253c2c41aa65c47c0cc21909c02e1aa800f9194d1e55ba25204b, 8602311b0e253f8ca8b0671ffe41296676a0df5aa0430d3936cd7287cdc7f394)), ((119aaf64404bcd37dd04d46d4a5610fb2c8b8846352369480f580930d1bacab2, aeb5d47b7231d14a51d48f521d7a9645e369dd19472f73c9c9461ea2194a8d4d), (311f62c61f7758f41d4e18d2a0c9781150f1b61cbf47d9dd5ee457b0bd858114, 0256efffe8875583c80bb5ac9a3922013e907e4bda5f54d466701464231ac584)), ((b520e00837db9507092b846caf84279ea4273110a40cf549175e8992bcd4ac15, 5f2266990cf25b5d64581fad0f6d058b1dab1a777dd5217f36d612e9b5d86883), (0adf5769e8367c758ec7d2032ee85ef15cb14eb8768d140fde9f18531c20d47e, 60f10107781302c5148c2c272b3f9f4396c4135aafafe0dc929dabee2a96a03c))), expected (((7f7d19d85f3602d345954a139354d3c21901e1a498d7450337c6871c7ed0ea64, 7b83e0ecad6e616e48b618729683f33e606c8ea9b073da6b2c3725791d45e8d8), (6ca7d15cbbaeb57c995123b041aca2f9ad23d6e3b7834c12e9c26a6af231d777, 9b29080b4e1e8e84bb7ea257c49c8488a3313d3bc3ca5d86dcfc5d312e7f622d)), ((b2028f6e33ce1c8f0f4b2ee0f2bdb6add1ea2b9d461e832c750cf2987107424f, 920641617a09ddabedef85f8f2894625dc563ec0333fe6d7c5e3e3a1985cfca3), (4d1eaf530e30ac1825cb388de9d4fea45abada079bd8cd79b6897e23c8b81f12, 2f8450b72e3e53a0c0abe3dd4422b93aefff6d8d585595b665a22d773dea48bc)), ((0d2492c399343534a0b49dda6750a135d766f7c23b05bdda2417bf81c4c4747c, 516eb30add5f91da3df80fb52c8469f82a7cb57b393332dc89c6ce9230eaa7e4), (67f12e4c84ef171a534b48da0413f857c0c7e0b3b905b3d6ea61430a858f11d3, 8fd6d693c9163c3715e94a0db5c47eec1cc6b406b6399537cac7bdee633fbf29)))
--- FAIL: Test_finalExponentiation (0.07s)
=== RUN TestG1BaseMult
g1_test.go:135: #1: got (69622fd48886da574b1df9391aec42c50019b4b2e1a88bd638359bd309c3b87f, 5d96360ee58a5a6840b3e8cad023e6c4081b3f91d70d7a811c4e9d44ac1c4f8e), want (98308a2cc761cd353d43546fb2f8b3a661d539acee2eee2f33347c295563f4b2, 5c8edf80776ea1ddca48a0cbb2fee68bd1ccbac88b2a814bc25b85d0d412a1fd)
g1_test.go:135: #2: got (1acf86d2c34ff59240b13642673d0c3dc474a9584b36b1d74b5c5044b05b0ea1, 335542c9c812f1871fca0bebf4edc5a2e1585d3271f8284aff566f697f786f7a), want (6ac1f0dd2548250f9ca4a3926e98b10e294b3dca9f52a9be66f106a105602554, 71bbfd12e9a21877b25af9f5ab96b9178bc072871e7cf2491291c84942a70aee)
g1_test.go:135: #3: got (aeb74f631a2caa4e2a536d2bc10327b9a8b3e4b34a9245b62d57b249637839b5, 4de0e1e2d8033a949ab5a2b4556950492cfce3e308708ef82e41702950a6feb), want (5f801a7846fd494756a2c774d3e70adc3dfe32a3eeee182440927290b335fce4, 90b13bf805932a7f7210c61f4d5dd59930b3ea816c5fe33c0c0e1b49c872066d)
g1_test.go:135: #4: got (4b429937a9a8afd4275e6a3d546649f2362fb04156281c168d8ca024d24488d0, 51c7b11ea4018e2386e5f3950b58abe10298ac74f2bcddd5eeefbc8fb0b56c00), want (8a6ec5753ba604ef8c67b74cd00768826da871f8a8ec814c128975a979d27e16, 37a7cf29db07308c7cf9dd2c5b7865c84c062decc6fcf65e1a2fd69e194c8c76)
g1_test.go:135: #5: got (4e83475f776ca1743d9a3b9a7b63e70f6d697abb55000af9153d7d78ec5d66ce, 603a403aba4247ad2abaf08fe69909cb4382a5b25d17782f744b6fc362767e02), want (2a6b8780b0bfe9d4e26a2cab6977904ec77fff42a41ce573431b0fc99741b470, 162b908e9ccbbbbcfa4b95194fc5be4cfbe1202e6d4b0cee0f1b6b108a5f7d1e)
g1_test.go:135: #6: got (3a2152d1e9e2567c286f389a509a5b27c5e8df6842c6309564617795c2dca960, 5fac73c0a3c0265f2132a309a200b68b2bd96d1796a636e32ad3b154f7af68e), want (4e23307000bfdfa62183a3446649818889314051c95daf09dd2823b988e21dd9, 6f10a46330806c07d8acc529c98c3bccc724e471bb1b715d9ecacdd996f53070)
--- FAIL: TestG1BaseMult (0.00s)
=== RUN TestFuzz
--- FAIL: TestFuzz (0.00s)
panic: sm9: ScalarMult was called on an invalid point [recovered]
panic: sm9: ScalarMult was called on an invalid point

goroutine 12 [running]:
testing.tRunner.func1.1(0x1628e0, 0x1c7960)
/home/travis/.gimme/versions/go1.15.15.linux.arm64/src/testing/testing.go:1072 +0x240
testing.tRunner.func1(0x4000001e00)
/home/travis/.gimme/versions/go1.15.15.linux.arm64/src/testing/testing.go:1075 +0x34c
panic(0x1628e0, 0x1c7960)
/home/travis/.gimme/versions/go1.15.15.linux.arm64/src/runtime/panic.go:969 +0x15c
github.com/emmansun/gmsm/sm9.(*G1Curve).ScalarMult(0x2a3bd0, 0x4000388060, 0x4000388080, 0x4000345f60, 0x20, 0x20, 0x4000434de0, 0x4000434e00)
/home/travis/gopath/src/github.com/emmansun/gmsm/sm9/g1.go:342 +0x240
github.com/emmansun/gmsm/sm9.TestFuzz(0x4000001e00)
/home/travis/gopath/src/github.com/emmansun/gmsm/sm9/g1_test.go:171 +0x1f0
testing.tRunner(0x4000001e00, 0x19eba0)
/home/travis/.gimme/versions/go1.15.15.linux.arm64/src/testing/testing.go:1123 +0xdc
created by testing.(*T).Run
/home/travis/.gimme/versions/go1.15.15.linux.arm64/src/testing/testing.go:1168 +0x244
FAIL github.com/emmansun/gmsm/sm9 0.125s

crypto/x509: add support for CertPool to load certs lazily

Sync this change crypto/x509: add support for CertPool to load certs lazily to smx509

This will allow building CertPools that consume less memory. (Most
certs are never accessed. Different users/programs access different
ones, but not many.)

This CL only adds the new internal mechanism (and uses it for the
old AddCert) but does not modify any existing root pool behavior.
(That is, the default Unix roots are still all slurped into memory as
of this CL)

导出sm2.PublicKey

请问可以添加导出sm2.PublicKey吗?

在实现协商密钥的时候需要单独用到sm2.PublicKey,需要和crypto包保持兼容。

// GenerateSharedSecret 生成共享密钥
func GenerateSharedSecret(priv crypto.PrivateKey, pub crypto.PublicKey) ([]byte, error) {
	var (
		x1    *big.Int
		y1    *big.Int
		k     []byte
		curve elliptic.Curve
	)
	switch key := priv.(type) {
	case *ecdsa.PrivateKey:
		k = key.D.Bytes()
		pubKey, ok := pub.(*ecdsa.PublicKey)
		if !ok { 
			return nil, errors.New("pub only support ecdsa.PublicKey point type")
		}
		x1 = pubKey.X
		y1 = pubKey.Y
		curve = pubKey.Curve
	case *sm2.PrivateKey:
		k = key.D.Bytes()
		pubKey, ok := pub.(*sm2.PublicKey)
		if !ok { 
			return nil, errors.New("pub only support sm2.PublicKey point type")
		}
		x1 = pubKey.X
		y1 = pubKey.Y
		curve = pubKey.Curve
	default: 
		return nil, errors.New("priv only support ecdsa.PrivateKey and sm2.PrivateKey")
	}
        x, _ := curve.ScalarMult(x1, y1, k)
	return x.Bytes(), nil
}

在平台supportsGFMUL为true但useAVX2为false时,SM4解密可能会发生错误:"cipher: message authentication failed"

现象

在平台supportsGFMUL为true但useAVX2为false时,SM4加解密可能会发生错误:"cipher: message authentication failed"。

测试案例

sm4/sm4_gcm_test.go中添加以下测试案例,当平台supportsGFMUL=true 且 useAVX2=false 时,该测试案例会失败,在解密时抛出"cipher: message authentication failed"的错误。

func TestGcmAsmWithNonce(t *testing.T) {
    // 打印平台对相关指令集的支持
	fmt.Println("supportSM4:", supportSM4) // false
	fmt.Println("supportsAES:", supportsAES) // true
	fmt.Println("supportsGFMUL:", supportsGFMUL) // true
	fmt.Println("useAVX2:", useAVX2) // false
    // 并不是百分百重现,目前只发现当supportsGFMUL=true 且 useAVX2=false 时,使用下面的数据测试会失败。
	key := []byte{251, 160, 47, 88, 53, 110, 220, 7, 229, 174, 145, 250, 40, 34, 188, 237}
	nonce := []byte{182, 244, 44, 22, 113, 249, 246, 127, 114, 94, 115, 60}
	dst := []byte{23, 3, 3, 2, 191}
	data := []byte{11, 0, 2, 170, 0, 0, 2, 166, 0, 2, 161, 48, 130, 2, 157, 48, 130, 2, 67, 160, 3, 2, 1, 2, 2, 17, 0, 179, 19, 43, 244, 221, 102, 20, 101, 125, 96, 139, 186, 249, 198, 195, 128, 48, 10, 6, 8, 42, 129, 28, 207, 85, 1, 131, 117, 48, 74, 49, 15, 48, 13, 6, 3, 85, 4, 10, 19, 6, 99, 97, 116, 101, 115, 116, 49, 20, 48, 18, 6, 3, 85, 4, 3, 19, 11, 99, 97, 46, 116, 101, 115, 116, 46, 99, 111, 109, 49, 11, 48, 9, 6, 3, 85, 4, 6, 19, 2, 67, 78, 49, 20, 48, 18, 6, 3, 85, 4, 8, 19, 11, 65, 110, 104, 117, 105, 32, 72, 101, 102, 101, 105, 48, 30, 23, 13, 50, 50, 48, 52, 49, 50, 48, 56, 53, 50, 48, 51, 90, 23, 13, 51, 50, 48, 52, 48, 57, 48, 57, 53, 50, 48, 51, 90, 48, 83, 49, 20, 48, 18, 6, 3, 85, 4, 10, 12, 11, 115, 101, 114, 118, 101, 114, 95, 116, 101, 115, 116, 49, 24, 48, 22, 6, 3, 85, 4, 3, 19, 15, 115, 101, 114, 118, 101, 114, 46, 116, 101, 115, 116, 46, 99, 111, 109, 49, 11, 48, 9, 6, 3, 85, 4, 6, 19, 2, 67, 78, 49, 20, 48, 18, 6, 3, 85, 4, 8, 19, 11, 65, 110, 104, 117, 105, 32, 72, 101, 102, 101, 105, 48, 90, 48, 20, 6, 8, 42, 129, 28, 207, 85, 1, 130, 45, 6, 8, 42, 129, 28, 207, 85, 1, 130, 45, 3, 66, 0, 4, 208, 246, 86, 87, 22, 133, 125, 168, 54, 91, 20, 197, 65, 195, 72, 121, 155, 195, 153, 47, 205, 174, 4, 237, 184, 164, 199, 171, 193, 125, 196, 244, 152, 160, 152, 212, 105, 20, 101, 74, 231, 154, 254, 71, 47, 116, 38, 82, 17, 16, 177, 44, 237, 56, 187, 48, 26, 125, 243, 220, 27, 128, 205, 173, 163, 129, 255, 48, 129, 252, 48, 14, 6, 3, 85, 29, 15, 1, 1, 255, 4, 4, 3, 2, 6, 192, 48, 29, 6, 3, 85, 29, 37, 4, 22, 48, 20, 6, 8, 43, 6, 1, 5, 5, 7, 3, 1, 6, 8, 43, 6, 1, 5, 5, 7, 3, 2, 48, 41, 6, 3, 85, 29, 14, 4, 34, 4, 32, 211, 20, 37, 161, 114, 121, 43, 88, 162, 253, 161, 74, 105, 189, 203, 192, 67, 227, 69, 174, 129, 131, 172, 208, 91, 24, 210, 108, 207, 72, 20, 121, 48, 43, 6, 3, 85, 29, 35, 4, 36, 48, 34, 128, 32, 72, 47, 170, 202, 171, 110, 250, 70, 1, 121, 23, 136, 94, 115, 82, 88, 94, 97, 91, 98, 5, 106, 154, 74, 111, 55, 129, 6, 143, 58, 220, 191, 48, 115, 6, 3, 85, 29, 17, 4, 108, 48, 106, 130, 15, 115, 101, 114, 118, 101, 114, 46, 116, 101, 115, 116, 46, 99, 111, 109, 130, 16, 116, 101, 115, 116, 46, 101, 120, 97, 109, 112, 108, 101, 46, 99, 111, 109, 129, 17, 103, 111, 112, 104, 101, 114, 64, 103, 111, 108, 97, 110, 103, 46, 111, 114, 103, 135, 4, 127, 0, 0, 1, 135, 16, 32, 1, 72, 96, 0, 0, 32, 1, 0, 0, 0, 0, 0, 0, 0, 104, 134, 26, 104, 116, 116, 112, 115, 58, 47, 47, 102, 111, 111, 46, 99, 111, 109, 47, 119, 105, 98, 98, 108, 101, 35, 102, 111, 111, 48, 10, 6, 8, 42, 129, 28, 207, 85, 1, 131, 117, 3, 72, 0, 48, 69, 2, 32, 118, 163, 224, 17, 60, 183, 70, 62, 5, 158, 223, 251, 62, 186, 40, 120, 53, 145, 196, 225, 9, 235, 5, 251, 224, 133, 172, 205, 181, 237, 2, 51, 2, 33, 0, 215, 113, 160, 193, 183, 1, 187, 104, 101, 175, 88, 66, 195, 191, 53, 200, 235, 175, 0, 33, 224, 189, 75, 215, 130, 219, 162, 54, 11, 183, 170, 216, 0, 0, 22}
	err := testGCMWithNonce(key, data, nonce, dst)
	if err != nil {
		t.Fatal(err)
	}
}

func testGCMWithNonce(key, data, nonce, dst []byte) error {
	encryptData, err := Sm4EncryptGcmWithNonce(data, key, nonce, dst)
	if err != nil {
		return err
	}
	fmt.Printf("GCM encryptData : %v\n", encryptData)

	plainData, err := Sm4DecryptGcmWithNonce(encryptData, key, nonce, dst)
	if err != nil {
		return err
	}
	fmt.Printf("GCM plainData : %v\n", plainData)
	return nil
}

func Sm4EncryptGcmWithNonce(plainData, key, nonce, dst []byte) (encryptData []byte, err error) {
	block, err := NewCipher([]byte(key))
	if err != nil {
		return nil, err
	}
	sm4gcm, err := cipher.NewGCM(block)
	if err != nil {
		return nil, err
	}
	out := sm4gcm.Seal(dst, nonce, plainData, dst)
	encryptData = out[len(dst):]
	return
}

func Sm4DecryptGcmWithNonce(encryptData, key, nonce, dst []byte) ([]byte, error) {
	block, err := NewCipher([]byte(key))
	if err != nil {
		return nil, err
	}
	sm4gcm, err := cipher.NewGCM(block)
	if err != nil {
		return nil, err
	}
	out, err := sm4gcm.Open(encryptData[:0], nonce, encryptData, dst)
	if err != nil {
		return nil, err
	}
	return out, nil
}

原因推测

sm4/cipher_asm.go的函数newCipher中,useAVX2为false时,blocks值为4;同时此时supportsGFMUL为true的话,会使用sm4/sm4_gcm_asm.gosm4CipherGCM初始化cipher.Block。此时是否不应该进入supportsGFMUL为true的逻辑?即,supportsGFMUL和useAVX2都为true时,才使用sm4CipherGCM。

做出如下修改(supportsGFMUL和useAVX2都为true时,才使用sm4CipherGCM)后,错误不再发生。

代码:sm4/cipher_asm.go,函数:newCipher,行数:92,尝试修改为:

func newCipher(key []byte) (cipher.Block, error) {
	if supportSM4 {
		return newCipherNI(key)
	}

	if !supportsAES {
		return newCipherGeneric(key)
	}

	blocks := 4
	if useAVX2 {
		blocks = 8
	}
	c := &sm4CipherAsm{sm4Cipher{make([]uint32, rounds), make([]uint32, rounds)}, blocks, blocks * BlockSize}
	expandKeyAsm(&key[0], &ck[0], &c.enc[0], &c.dec[0], INST_AES)
	// if supportsGFMUL {
	if supportsGFMUL && useAVX2 {
		return &sm4CipherGCM{c}, nil
	}
	return c, nil
}

[sync] crypto/x509: use SAN when comparing certs during path building

Per RFC 4158 Section 2.4.2, when we are discarding candidate
certificates during path building, use the SANs as well as subject and
public key when checking whether a certificate is already present in
the built path. This supports the case where a certificate in the chain
(typically a leaf) has the exact same subject and public key as another
certificate in the chain (typically its parent) but has SANs which don't
match.

[go1.18] internal/subtle xor 简化代码,去除重复

amd64/arm64使用指针:

//go:noescape
func xorBytes(dst, a, b *byte, n int)

而generic实现使用切片:

// fastXORBytes xors in bulk. It only works on architectures that
// support unaligned read/writes.
// n needs to be smaller or equal than the length of a and b.
func fastXORBytes(dst, a, b []byte, n int) {

golang 1.17提供了unsafe.Slice方法,可用用来简化代码:

func xorBytes(dstb, xb, yb *byte, n int) {
	// xorBytes assembly is written using pointers and n. Back to slices.
	dst := unsafe.Slice(dstb, n)
	x := unsafe.Slice(xb, n)
	y := unsafe.Slice(yb, n)
...
}

关于蒙哥马利简约实现

想问一下这里面的实现细节,
1.这里的position指的是哪里?

// At position 86, which is the starting bit position for word 3, we

2.这个 have a factor of 0xffffc00 = 2^29 - 2^11的意思是什么?
// have a factor of 0x1ffff800 = 2**29 - 2**11

3./ Word: 2 3 4 5 6 7 8 9 10
// Added in top half: 29 28 29 29 29 29 29 28
// 29 28 29 28 29
// 29
// Added in bottom half: 28 29 28 28 28 29 28 28
// 28 29 28 29 28
这个表得意思不是很理解。

SM2 TLS

Greetings!

I'm having issue with TLS 1.2 implementation with SM2 curve, more specifically with certificate generation:

var privatekey *ecdsa.PrivateKey
var pubkey ecdsa.PublicKey
var public *ecdsa.PublicKey
var err error
var pubkeyCurve elliptic.Curve

pubkeyCurve = sm2.P256()

if *pkey == "certgen" {
	file, err := os.Open(*key)
	if err != nil {
		log.Println(err)
	}
	info, err := file.Stat()
	if err != nil {
		log.Println(err)
	}
	buf := make([]byte, info.Size())
	file.Read(buf)

	var priv interface{}

	var block *pem.Block
	block, _ = pem.Decode(buf)

	if *alg == "SM2" {
		var privateKey *ecdsa.PrivateKey
		var privKeyBytes []byte
		if x509.IsEncryptedPEMBlock(block) {
			privKeyBytes, err = smx509.DecryptPEMBlock(block, []byte(*pwd))
			if err != nil {
				log.Fatal(err)
			}
			privateKey, err = smx509.ParseECPrivateKey(privKeyBytes)
			if err != nil {
				log.Fatal(err)
			}
		} else {
			privateKey, err = smx509.ParseECPrivateKey(block.Bytes)
			if err != nil {
				log.Fatal(err)
			}
		}
		priv = privateKey
	} 

	keyUsage := smx509.KeyUsageDigitalSignature

	serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 160)
	serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
	if err != nil {
		log.Fatalf("Failed to generate serial number: %v", err)
	}

	consensus := externalip.DefaultConsensus(nil, nil)
	ip, _ := consensus.ExternalIP()

	Mins := 1200
	NotAfter := time.Now().Local().Add(time.Minute * time.Duration(Mins))

	scanner := bufio.NewScanner(os.Stdin)

	fmt.Print("CommonName: ")
	scanner.Scan()
	name := scanner.Text()

	fmt.Print("Country: ")
	scanner.Scan()
	country := scanner.Text()

	fmt.Print("State/Province: ")
	scanner.Scan()
	province := scanner.Text()

	fmt.Print("Locality: ")
	scanner.Scan()
	locality := scanner.Text()

	fmt.Print("Organization: ")
	scanner.Scan()
	organization := scanner.Text()

	fmt.Print("OrganizationUnit: ")
	scanner.Scan()
	organizationunit := scanner.Text()

	fmt.Print("Email: ")
	scanner.Scan()
	email := scanner.Text()

	fmt.Print("StreetAddress: ")
	scanner.Scan()
	street := scanner.Text()

	fmt.Print("PostalCode: ")
	scanner.Scan()
	postalcode := scanner.Text()

	fmt.Print("SerialNumber: ")
	scanner.Scan()
	number := scanner.Text()

	fmt.Print("AuthorityKeyId: ")
	scanner.Scan()
	authority, _ := hex.DecodeString(scanner.Text())

	template := x509.Certificate{
		SerialNumber: serialNumber,
		Subject: pkix.Name{
			CommonName: name,
			SerialNumber: number,
			Country: []string{country},
			Province: []string{province},
			Locality: []string{locality},
			Organization: []string{organization},
			OrganizationalUnit: []string{organizationunit},
			StreetAddress: []string{street},
			PostalCode: []string{postalcode},
		},
		EmailAddresses:              []string{email},

		NotBefore: time.Now(),
		NotAfter:  NotAfter,

		KeyUsage:              keyUsage,
		ExtKeyUsage:           []smx509.ExtKeyUsage{smx509.ExtKeyUsageServerAuth},
		BasicConstraintsValid: true,
		IsCA:                  true,
		AuthorityKeyId:        authority,

		PermittedDNSDomainsCritical: true,
		DNSNames:                    []string{ip.String()},
		IPAddresses:                 []net.IP{net.IPv4(127, 0, 0, 1).To4(), net.ParseIP("2001:4860:0:2001::68")},
	}

	template.IsCA = true
	template.KeyUsage |= smx509.KeyUsageCertSign

	derBytes, err := smx509.CreateCertificate(rand.Reader, &template, &template, publicKey(priv), priv)
	if err != nil {
		log.Fatalf("Failed to create certificate: %v", err)
	}

	certfile, err := os.Create(*cert)
	if err != nil {
		log.Println(err)
	}
	pem.Encode(certfile, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
	os.Exit(0)
}

Failed to create certificate: x509: signature over certificate returned by signer is invalid: x509: ECDSA verification failure.

And I have two more questions:
Do the BN256 and SM9 support TLS? If yes, how to summon them? I mean, with SM2 pubkeyCurve = sm2.P256() but there is no interface to SM9 like pubkeyCurve = sm9.P256() or pubkeyCurve = bn.P256() , how to proceed?

Thanks in advance.

[go1.19] crypto/x509: add new CRL parser, deprecate old one

golang/go@2de2f6d

Adds a new, cryptobyte based, CRL parser, which returns a
x509.RevocaitonList, rather than a pkix.CertificateList. This allows us
to return much more detailed information, as well as leaving open the
option of adding further information since RevocationList is not a
direct ASN.1 representation like pkix.CertificateList. Additionally
a new method is added to RevocationList, CheckSignatureFrom, which is
analogous to the method with the same name on Certificate, which
properly checks that the signature is from an issuing certiifcate.

This change also deprecates a number of older CRL related functions and
types, which have been replaced with the new functionality introduced
in this change:

  • crypto/x509.ParseCRL
  • crypto/x509.ParseDERCRL
  • crypto/x509.CheckCRLSignature
  • crypto/x509/pkix.CertificateList
  • crypto/x509/pkix.TBSCertificateList

skf接口导出共钥转pem问题

typedef struct Struct_ECCPUBLICKEYBLOB{
ULONG BitLen;
BYTE XCoordinate[ECC_MAX_XCOORDINATE_BITS_LEN/8];
BYTE YCoordinate[ECC_MAX_YCOORDINATE_BITS_LEN/8];
}ECCPUBLICKEYBLOB, *PECCPUBLICKEYBLOB;

想吧这个转为pem格式的pubkey,有参考的说明吗

统一文件换行符

现在大部分文件是以 CRLF 换行,但还是有几个文件是以 LF 换行的。
是否可以统一一下。

$ find . -type f -not -path '*/\.git/*' -and -not -path '*/\.idea/*' -print0 | xargs -0 file | grep -w text | grep 'with CRLF line terminators' | wc -l
74

$ find . -type f -not -path '*/\.git/*' -and -not -path '*/\.idea/*' -print0 | xargs -0 file | grep -w text | grep -v 'with CRLF line terminators'
./sm4/cipher_test.go:           ASCII text
./sm3/sm3_test.go:              Unicode text, UTF-8 text, with very long lines (576)
./sm2/util_test.go:             ASCII text
./sm2/sm2_test.go:              ASCII text
./smx509/x509_test.go:          Unicode text, UTF-8 text, with very long lines (1023)
./LICENSE:                      ASCII text
./README.md:                    Unicode text, UTF-8 text, with very long lines (342)
./.gitignore:                   ASCII text
./go.mod:                       ASCII text

[sync] crypto/x509: fix EKU nesting enforcement

The path building rework broke the enforcement of EKU nesting, this
change goes back to using the old method of enforcement, since it ends
up being more efficient to check the chains after building, rather than
at each step during path building.

Reference #39

关于Go Crypto

您好,请问您是否有有意向Go官方库提交关于SM系列算法的PR?

这个是我的个人想法。

谢谢作者

linux/arm64 编译报错

$ GOOS=linux GOARCH=arm64 go build ./...
# github.com/emmansun/gmsm/sm4
asm: illegal combination: 00308 (/code/github.com/emmansun/gmsm/sm4/asm_arm64.s:256)   VDUP    R19, V0.S4 REG NONE NONE ARNG, 7 7
asm: illegal combination: 00428 (/code/github.com/emmansun/gmsm/sm4/asm_arm64.s:264)   VDUP    R19, V0.S4 REG NONE NONE ARNG, 7 7
asm: illegal combination: 00548 (/code/github.com/emmansun/gmsm/sm4/asm_arm64.s:272)   VDUP    R19, V0.S4 REG NONE NONE ARNG, 7 7
asm: illegal combination: 00668 (/code/github.com/emmansun/gmsm/sm4/asm_arm64.s:280)   VDUP    R19, V0.S4 REG NONE NONE ARNG, 7 7
asm: illegal combination: 00308 (/code/github.com/emmansun/gmsm/sm4/asm_arm64.s:256)   VDUP    R19, V0.S4 REG NONE NONE ARNG, 7 7
asm: illegal combination: 00428 (/code/github.com/emmansun/gmsm/sm4/asm_arm64.s:264)   VDUP    R19, V0.S4 REG NONE NONE ARNG, 7 7
asm: illegal combination: 00548 (/code/github.com/emmansun/gmsm/sm4/asm_arm64.s:272)   VDUP    R19, V0.S4 REG NONE NONE ARNG, 7 7
asm: illegal combination: 00668 (/code/github.com/emmansun/gmsm/sm4/asm_arm64.s:280)   VDUP    R19, V0.S4 REG NONE NONE ARNG, 7 7
asm: illegal combination: 00308 (/code/github.com/emmansun/gmsm/sm4/asm_arm64.s:256)   VDUP    R19, V0.S4 REG NONE NONE ARNG, 7 7
asm: illegal combination: 00428 (/code/github.com/emmansun/gmsm/sm4/asm_arm64.s:264)   VDUP    R19, V0.S4 REG NONE NONE ARNG, 7 7
asm: illegal combination: 00548 (/code/github.com/emmansun/gmsm/sm4/asm_arm64.s:272)   VDUP    R19, V0.S4 REG NONE NONE ARNG, 7 7
asm: illegal combination: 00668 (/code/github.com/emmansun/gmsm/sm4/asm_arm64.s:280)   VDUP    R19, V0.S4 REG NONE NONE ARNG, 7 7
asm: illegal combination: 00308 (/code/github.com/emmansun/gmsm/sm4/asm_arm64.s:256)   VDUP    R19, V0.S4 REG NONE NONE ARNG, 7 7
asm: illegal combination: 00428 (/code/github.com/emmansun/gmsm/sm4/asm_arm64.s:264)   VDUP    R19, V0.S4 REG NONE NONE ARNG, 7 7
asm: illegal combination: 00548 (/code/github.com/emmansun/gmsm/sm4/asm_arm64.s:272)   VDUP    R19, V0.S4 REG NONE NONE ARNG, 7 7
asm: illegal combination: 00668 (/code/github.com/emmansun/gmsm/sm4/asm_arm64.s:280)   VDUP    R19, V0.S4 REG NONE NONE ARNG, 7 7
asm: illegal combination: 00244 (/code/github.com/emmansun/gmsm/sm4/asm_arm64.s:342)   VDUP    R19, V0.S4 REG NONE NONE ARNG, 7 7
asm: illegal combination: 00364 (/code/github.com/emmansun/gmsm/sm4/asm_arm64.s:350)   VDUP    R19, V0.S4 REG NONE NONE ARNG, 7 7
asm: illegal combination: 00484 (/code/github.com/emmansun/gmsm/sm4/asm_arm64.s:358)   VDUP    R19, V0.S4 REG NONE NONE ARNG, 7 7
asm: illegal combination: 00604 (/code/github.com/emmansun/gmsm/sm4/asm_arm64.s:366)   VDUP    R19, V0.S4 REG NONE NONE ARNG, 7 7
asm: illegal combination: 00244 (/code/github.com/emmansun/gmsm/sm4/asm_arm64.s:342)   VDUP    R19, V0.S4 REG NONE NONE ARNG, 7 7
asm: illegal combination: 00364 (/code/github.com/emmansun/gmsm/sm4/asm_arm64.s:350)   VDUP    R19, V0.S4 REG NONE NONE ARNG, 7 7
asm: illegal combination: 00484 (/code/github.com/emmansun/gmsm/sm4/asm_arm64.s:358)   VDUP    R19, V0.S4 REG NONE NONE ARNG, 7 7
asm: illegal combination: 00604 (/code/github.com/emmansun/gmsm/sm4/asm_arm64.s:366)   VDUP    R19, V0.S4 REG NONE NONE ARNG, 7 7
asm: illegal combination: 00244 (/code/github.com/emmansun/gmsm/sm4/asm_arm64.s:342)   VDUP    R19, V0.S4 REG NONE NONE ARNG, 7 7
asm: illegal combination: 00364 (/code/github.com/emmansun/gmsm/sm4/asm_arm64.s:350)   VDUP    R19, V0.S4 REG NONE NONE ARNG, 7 7
asm: illegal combination: 00484 (/code/github.com/emmansun/gmsm/sm4/asm_arm64.s:358)   VDUP    R19, V0.S4 REG NONE NONE ARNG, 7 7
asm: illegal combination: 00604 (/code/github.com/emmansun/gmsm/sm4/asm_arm64.s:366)   VDUP    R19, V0.S4 REG NONE NONE ARNG, 7 7
asm: illegal combination: 00244 (/code/github.com/emmansun/gmsm/sm4/asm_arm64.s:342)   VDUP    R19, V0.S4 REG NONE NONE ARNG, 7 7
asm: illegal combination: 00364 (/code/github.com/emmansun/gmsm/sm4/asm_arm64.s:350)   VDUP    R19, V0.S4 REG NONE NONE ARNG, 7 7
asm: illegal combination: 00484 (/code/github.com/emmansun/gmsm/sm4/asm_arm64.s:358)   VDUP    R19, V0.S4 REG NONE NONE ARNG, 7 7
asm: illegal combination: 00604 (/code/github.com/emmansun/gmsm/sm4/asm_arm64.s:366)   VDUP    R19, V0.S4 REG NONE NONE ARNG, 7 7
asm: assembly failed
$ git rev-parse --verify HEAD
acabed56bd8c6e45ab58817cdf1af5cb145f8930

$ go version
go version go1.15.15 linux/amd64

Mac 无法运行,window/linux 下是正常的,麻烦大佬,看一下

github.com/emmansun/gmsm/smx509

../../../../pkg/mod/github.com/emmansun/[email protected]/smx509/cert_pool.go:112:9: undefined: loadSystemRoots
../../../../pkg/mod/github.com/emmansun/[email protected]/smx509/root.go:17:32: undefined: loadSystemRoots
../../../../pkg/mod/github.com/emmansun/[email protected]/smx509/verify.go:648:4: not enough arguments to return
../../../../pkg/mod/github.com/emmansun/[email protected]/smx509/verify.go:648:12: c.systemVerify undefined (type *Certificate has no field or method systemVerify)
../../../../pkg/mod/github.com/emmansun/[email protected]/smx509/verify.go:651:28: c.systemVerify undefined (type *Certificate has no field or method systemVerify)

[go1.17] sm2p256_asm.go中切片直接转数组指针

这个语言特性是golang 1.17引入的,目前只能用以下代码代替:

// toElementArray, convert slice of bytes to pointer to [32]byte.
// This function is required for low version of golang, can type cast directly
// since golang 1.17 .
func toElementArray(b []byte) *[32]byte {
	tmpPtr := (*unsafe.Pointer)(unsafe.Pointer(&b))
	return (*[32]byte)(*tmpPtr)
}

sm2: encryption support ASN.1 encoding format

HUAWEI Cloud KMS (DEW) sm2 encryption result is ASN.1 encoding fomat.

密文编码问题

SM2密文由C1、C2、C3三部分构成,如何对SM2密文进行编码在已经公布的两个标准中有所不同,在早期公布的《SM2椭圆曲线公钥密码算法 第4部分:公钥加密算法》中,SM2密文中的三部分依次输出,没有采用如Tag-Length-Value形式的编码,我们称其为Plain编码。在之后公布的GM/T国标中,SM2密文采用ASN.1/DER方式编码。

GmSSL通过SM2_CIPHERTEXT_VALUE对象来表示密文数据结构,函数SM2_do_encrypt()和SM2_do_decrypt()可以生成SM2_CIPHERTEXT_VALUE对象及对其解密,函数SM2_CIPHERTEXT_VALUE_encode()和SM2_CIPHERTEXT_VALUE_decode()实现该对象的Plain编解码。GmSSL预计还会通过函数i2d_SM2_CIPHERTEXT_VALUE()和d2i_SM2_CIPHERTEXT_VALUE()实现该密文对象的ASN.1/DER编解码,以支持最新的GM/T国密标准。

GmSSL的SM2_encrypt()和SM2_decrypt()在加解密的同时也完成SM2_CIPHERTEXT_VALUE对象的编解码。目前采用Plain编解码,在相应功能完成后会替换为ASN.1/DER编码方案。

[sync sdk] crypto/x509: don't panic marshaling invalid ECDSA keys

MarshalPKIXPublicKey, CreateCertificate, CreateCertificateRequest,
MarshalECPrivateKey, and MarshalPKCS8PrivateKey started raising a panic
when encoding an invalid ECDSA key in Go 1.19. Since they have an error
return value, they should return an error instead.

sm9/bn256.fromBigInt 初始化报错

你好!sm9/bn256.fromBigInt 初始化报错,希望可以有个解决方法
报错信息:
panic: runtime error: index out of range [4] with length 4
goroutine 1 [running]:
github.com/emmansun/gmsm/sm9/bn256.fromBigInt(0x887b20)
/root/go/pkg/mod/github.com/emmansun/[email protected]/sm9/bn256/gfp.go:40 +0x2a4
github.com/emmansun/gmsm/sm9/bn256.init()
/root/go/pkg/mod/github.com/emmansun/[email protected]/sm9/bn256/constants.go:57 +0x388

我现在用的运行程序开发板ARM版本,系统为uboot20.04,内核为4.9.88,
编写程序为wsl-20.04,go版本为go version go1.18.2 linux/amd64

请求公布 sm2.CalculateZA() 方法

背景:
我在用 tjfoc/gmsm emmansun/gmsm 缝合国密 tls 库,现在已经替换掉一部分代码。
现在有个 keyExchange() 方法,里面想改成调用 emmansun/gmsm 中的 sm2.CalculateZA()

见:

// keyExchange 为SM2密钥交换算法的第二部和第三步复用部分,协商的双方均调用此函数计算共同的字节串
// ...
func keyExchange(klen int, ida, idb []byte, pri *PrivateKey, pub *PublicKey, rpri *PrivateKey, rpub *PublicKey, thisISA bool) (k, s1, s2 []byte, err error) {

crypto/ecdsa: draw a fixed amount of entropy while signing

crypto/ecdsa: draw a fixed amount of entropy while signing

The current code, introduced in CL 2422, mixes K bits of entropy with
the private key and message digest to generate the signature nonce,
where K is half the bit size of the curve. While the ECDLP complexity
(and hence security level) of a curve is half its bit size, the birthday
bound on K bits is only K/2. For P-224, this means we should expect a
collision after 2^56 signatures over the same message with the same key.

A collision, which is unlikely, would still not be a major practical
concern, because the scheme would fall back to a secure deterministic
signature scheme, and simply leak the fact that the two signed messages
are the same (which is presumably already public).

Still, we can simplify the code and remove the eventuality by always
drawing 256 bits of entropy.

TLS support.

Will TLS modules be added? And support TLS 1.3.

[sync] crypto/x509: don't create certs with negative serials

Refuse to create certificates with negative serial numbers, as they
are explicitly disallowed by RFC 5280.

We still allow parsing certificates with negative serial numbers,
because in the past there were buggy CA implementations which would
produce them (although there are currently no trusted certificates
that have this issue). We may want to revisit this decision if we can
find metrics about the prevalence of this issue in enterprise settings.

sm2p256椭圆曲线方程没有使用sm2国密标准规定的"y^2 = x^3 + ax + b"吗?

作者你好,我学习了您的sm2的实现代码,注意到一个细节:您似乎没有使用国密标准"GB/T 32918.5-2017"中规定的椭圆曲线方程:y² = x³ + ax + b,而是沿用了ecdsa的方程:y² = x³ - 3x + b。这是什么原因呢?
比如:

  1. 您在定义sm2p256椭圆曲线参数时,没有指定方程参数a的值,比如"sm2/p256_asm.go"的"initP256"函数。
  2. 在"sm2/util.go"中根据x计算y的函数"calculatePrimeCurveY"中,实际使用的方程是ecdsa的"y² = x³ - 3x + b"

gmsm库支持对基于1.2.156.10197.1.301 sm2-1数字签名算法的公钥或证书,进行读取和验签操作吗

hi,勤劳的开发者们,

请问gmsm库支持对基于1.2.156.10197.1.301 sm2-1数字签名算法的公钥或证书,进行读取和验签操作吗

我获取了一份国密证书,但在加载证书时报错msg为:x509: not sm2 elliptic curve

代码片段为:
pubKey, err := x509.ReadPublicKeyFromPem(content) // 读取公钥
if err != nil || pubKey == nil {
fmt.Println("failed to read cert file, error is", err)
return
}

请问这个功能可用吗,是否有现有可用的函数可以使用,感谢。

best wishes

[sync] crypto/x509: rework path building

golang/go@65153e4

This change does four things:

  • removes the chain cache
  • during path building, equality is determined by checking if the
    subjects and public keys match, rather than checking if the entire
    certificates are equal
  • enforces EKU suitability during path building
  • enforces name constraints on intermediates and roots which have
    SANs during path building

The chain cache is removed as it was causing duplicate chains to be
returned, in some cases shadowing better, shorter chains if a longer
chain was found first.

Checking equality using the subjects and public keys, rather than the
entire certificates, allows the path builder to ignore chains which
contain cross-signature loops.

EKU checking is done during path building, as the previous behavior
of only checking EKUs once the path had been built caused the path
builder to incorrectly ignore valid paths when it encountered a path
which would later be ruled invalid because of unacceptable EKU usage.

Name constraints are applied uniformly across all certificates, not
just leaves, in order to be more consistent.

提议:smx509 包用 type alias 来减少与标准库的代码差异

如:

type PEMCipher = x509.PEMCipher

const (
	PEMCipherDES    = x509.PEMCipherDES
	PEMCipher3DES   = x509.PEMCipher3DES
	PEMCipherAES128 = x509.PEMCipherAES128
	PEMCipherAES192 = x509.PEMCipherAES192
	PEMCipherAES256 = x509.PEMCipherAES256
)

type PublicKeyAlgorithm = x509.PublicKeyAlgorithm
...

另外 Certificate 和 CertificateRequest 似乎可以改成:

type Certificate x509.Certificate
type CertificateRequest x509.CertificateRequest

来减少与标准库的代码差异。

如果可以这么做,我可以提交PR。

关于LoongArch支持

作者您好:

我在golang 1.19版本发布说明中发现,在1.19版本下支持了 龙芯 的 LoongArch 64-bit 指令集。

请问作者您后续是否考虑基于 LoongArch 64-bit 指令集 进行算法性能优化

[X509] simplify ParsePKIXPublicKey

现在 parsePublicKey()namedCurveFromOID() 已经支持了 oidNamedCurveP256SM2
貌似 ParsePKIXPublicKey() 没必要再对 oidNamedCurveP256SM2 单独处理了。

是否可以简化一下,直接用标准库一样的方法体
easyops-cn@40159e6

可以的话我就提个PR

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.