1 Star 1 Fork 0

zhuyuns/basic

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
rsa.go 2.00 KB
一键复制 编辑 原始数据 按行查看 历史
wing 提交于 2021-12-18 11:42 . 添加基础包
package rsa
import (
"bytes"
"crypto"
"errors"
)
type Cipher interface {
Encrypt(plainText []byte) ([]byte, error)
Decrypt(cipherText []byte) ([]byte, error)
Sign(src []byte, hash crypto.Hash) ([]byte, error)
Verify(src []byte, sign []byte, hash crypto.Hash) error
}
func NewCipher(key Key, padding Padding, cipherMode CipherMode, signMode SignMode) Cipher {
return &cipher{key: key, padding: padding, cipherMode: cipherMode, sign: signMode}
}
type cipher struct {
key Key
cipherMode CipherMode
sign SignMode
padding Padding
}
func (cipher *cipher) Encrypt(plainText []byte) ([]byte, error) {
groups := cipher.padding.Padding(plainText)
buffer := bytes.Buffer{}
for _, plainTextBlock := range groups {
cipherText, err := cipher.cipherMode.Encrypt(plainTextBlock, cipher.key.PublicKey())
if err != nil {
return nil, err
}
buffer.Write(cipherText)
}
return buffer.Bytes(), nil
}
func (cipher *cipher) Decrypt(cipherText []byte) ([]byte, error) {
if len(cipherText) == 0 {
return nil, errors.New("密文不能为空")
}
groups := grouping(cipherText, cipher.key.Modulus())
buffer := bytes.Buffer{}
for _, cipherTextBlock := range groups {
plainText, err := cipher.cipherMode.Decrypt(cipherTextBlock, cipher.key.PrivateKey())
if err != nil {
return nil, err
}
buffer.Write(plainText)
}
return buffer.Bytes(), nil
}
func (cipher *cipher) Sign(src []byte, hash crypto.Hash) ([]byte, error) {
return cipher.sign.Sign(src, hash, cipher.key.PrivateKey())
}
func (cipher *cipher) Verify(src []byte, sign []byte, hash crypto.Hash) error {
return cipher.sign.Verify(src, sign, hash, cipher.key.PublicKey())
}
func NewRSA(key Key) (Cipher, error) {
padding := NewPKCS1Padding(key.Modulus())
cipherMode := NewPKCS1v15Cipher()
signMode := NewPKCS1v15Sign()
return NewCipher(key, padding, cipherMode, signMode), nil
}
func NewRSAWith(key Key, padding Padding, cipherMode CipherMode, signMode SignMode) (Cipher, error) {
return NewCipher(key, padding, cipherMode, signMode), nil
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/zhuyuns/basic.git
git@gitee.com:zhuyuns/basic.git
zhuyuns
basic
basic
v0.0.68

搜索帮助