Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

缺失方法导入公钥然后使用公钥加密 #193

Open
jiftle opened this issue Sep 15, 2023 · 0 comments
Open

缺失方法导入公钥然后使用公钥加密 #193

jiftle opened this issue Sep 15, 2023 · 0 comments

Comments

@jiftle
Copy link

jiftle commented Sep 15, 2023

附代码

func SM2_GenerateKeyPair() (publicKey string, privateKey string, err error) {
	privKey, err := sm2.GenerateKey(nil) // 生成密钥对
	if err != nil {
		return
	}
	privateKey = x509.WritePrivateKeyToHex(privKey)
	publicKey = x509.WritePublicKeyToHex(&privKey.PublicKey)
	return
}

func SM2_PublicKey_Encrypt(plain string, publicKey string) (cipher string, err error) {
	pub, err := x509.ReadPublicKeyFromHex(publicKey)
	if err != nil {
		return
	}
	bytPlan, err := hex.DecodeString(plain)
	if err != nil {
		return
	}
	d, err := sm2.Encrypt(pub, bytPlan, rand.Reader, sm2.C1C3C2)
	if err != nil {
		return
	}
	cipher = hex.EncodeToString(d)
	return
}

func SM2_PrivateKey_Decrypt(cipher string, privKey string) (plain string, err error) {
	// g.Log().Infof(context.TODO(), "cipher=%v, privKey=%v", cipher, privKey)
	priv, err := x509.ReadPrivateKeyFromHex(privKey)
	if err != nil {
		return
	}
	bytCipher, err := hex.DecodeString(cipher)
	if err != nil {
		return
	}
	d, err := sm2.Decrypt(priv, bytCipher, sm2.C1C3C2)
	if err != nil {
		return
	}
	plain = hex.EncodeToString(d)
	// g.Log().Infof(context.TODO(), "cipher=%v, privKey=%v, plain=%v", cipher, privKey, plain)
	return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant