duke-git / lancet

A comprehensive, efficient, and reusable util function library of Go.

Home Page:https://www.golancet.cn/en/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

GenerateRsaKey 能否直接输出[]Byte

shaoerkuai opened this issue · comments

目前打算RSA简单加解密部分都用lancet实现,但是创建密钥时GenerateRsaKey 需要导出文件,能否直接允许返回byte[]

目前用的是x509.MarshalPKIXPublicKey,用的crypto包生成rsa的密钥,再通过x509转byte

@shaoerkuai 类似以下函数吗

func GenerateRsaKeyPair(keySize int) (*rsa.PrivateKey, *rsa.PublicKey)

可以,下个版本v2.2.7会添加支持。

@shaoerkuai 以下设计,符合你的rsa加密业务需求吗?

// GenerateRsaKeyPair create rsa private and public key.
func GenerateRsaKeyPair(keySize int) (*rsa.PrivateKey, *rsa.PublicKey) {
	privateKey, _ := rsa.GenerateKey(rand.Reader, keySize)
	return privateKey, &privateKey.PublicKey
}

// RsaEncryptOAEP encrypts the given data with RSA-OAEP.
func RsaEncryptOAEP(data []byte, label []byte, key rsa.PublicKey) ([]byte, error) {
	encryptedBytes, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, &key, data, label)
	if err != nil {
		return nil, err
	}

	return encryptedBytes, nil
}

// RsaDecryptOAEP decrypts the data with RSA-OAEP.
func RsaDecryptOAEP(ciphertext []byte, label []byte, key rsa.PrivateKey) ([]byte, error) {
	decryptedBytes, err := rsa.DecryptOAEP(sha256.New(), rand.Reader, &key, ciphertext, label)
	if err != nil {
		return nil, err
	}

	return decryptedBytes, nil
}

可以,很符合,棒

v2.2.7版本已支持。