Skip to content

Commit

Permalink
feat: improve code
Browse files Browse the repository at this point in the history
  • Loading branch information
houseme committed Mar 14, 2024
1 parent 6f9ec6d commit 02d12a0
Show file tree
Hide file tree
Showing 5 changed files with 29 additions and 33 deletions.
2 changes: 1 addition & 1 deletion .github/FUNDING.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
liberapay: "houseme" # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
Expand Down
31 changes: 16 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# GoCrypto使用说明
# GoCrypto 使用说明

[![Go Reference](https://pkg.go.dev/badge/github.com/houseme/gocrypto.svg)](https://pkg.go.dev/github.com/houseme/gocrypto)
[![GoCrypto CI](https://github.com/houseme/gocrypto/actions/workflows/go.yml/badge.svg)](https://github.com/houseme/gocrypto/actions/workflows/go.yml)
Expand All @@ -16,8 +16,8 @@ packaging:
- The incoming return uses the string type uniformly to avoid conversion trouble
- Supports RSAWithSHA1 and RSAWithSHA256 signature verification algorithms

此版本新增了AES、DES、3DES、HMAC、HASH等常见加/解密及hash获取方式,结构作了些调整,由之前的版本更新到此版本时一定要注意引用方法包名的变化。 AES/DES块加密时,填充默认采用PKCS7 padding(
如果块大小为64 位(8字节)时,此时PKCS7与PKCS5结果一致).
此版本新增了 AES、DES、3DES、HMAC、HASH 等常见加/解密及 hash 获取方式,结构作了些调整,由之前的版本更新到此版本时一定要注意引用方法包名的变化。AES/DES 块加密时,填充默认采用 PKCS7 padding(
如果块大小为 64 位(8 字节)时,此时 PKCS7 与 PKCS5 结果一致).

## get & import

Expand All @@ -29,7 +29,7 @@ go get -u -v github.com/houseme/gocrypto

## 使用方法

### 1.构建需要加解密的类型handle
### 1.构建需要加解密的类型 handle

```go
handleRSA := rsa.NewRSACrypt(secretInfo) // RSA
Expand Down Expand Up @@ -63,11 +63,12 @@ go get -u -v github.com/houseme/gocrypto
哈希运算/密钥相关的哈希运算。

```go
handle.Get([]byte("123456"))// 输出[]byte
handle.EncodeToString([]byte("123456"), gocrypto.HEX) // 输出为hex格式的字符串
handle.Get([]byte("123456"))// 输出 []byte
handle.EncodeToString([]byte("123456"), gocrypto.HEX) // 输出为 hex 格式的字符串

```

## RSA加密、解密、签名、验签
## RSA 加密、解密、签名、验签

### 1.设置公私钥信息

Expand All @@ -85,7 +86,7 @@ handle := rsa.NewRSACrypt(secretInfo)

### 加密、解密、签名、验签

#### (1)RSA加密
#### (1)RSA 加密

加密指定字符串,并以指定编码格式输出结果

Expand All @@ -98,7 +99,7 @@ if err != nil {
fmt.Println("encrypt data :", encrypt)
```

#### (2)RSA解密
#### (2)RSA 解密

解密指定格式编码后的加密串,返回原字符串

Expand All @@ -111,9 +112,9 @@ if err != nil {
fmt.Println("decrypt data :", decrypt)
```

#### (3)RSA签名
#### (3)RSA 签名

以指定摘要算法签名,并以指定编码格式输出结果,仅适用于RSA
以指定摘要算法签名,并以指定编码格式输出结果,仅适用于 RSA

```go
sign, err := handle.Sign("test", gocrypto.HEX)
Expand All @@ -124,9 +125,9 @@ if err != nil {
fmt.Println("sign data :", sign)
```

#### (4)RSA验签
#### (4)RSA 验签

验证字符串是否是以指定摘要算法编码的签名串的原始字符串,仅适用于RSA
验证字符串是否是以指定摘要算法编码的签名串的原始字符串,仅适用于 RSA

```go
verifySign, err := handle.VerifySign("test", sign, gocrypto.HEX)
Expand All @@ -137,7 +138,7 @@ if err != nil {
fmt.Println("verifySign result :", verifySign)
```

#### (5)RSA私钥加密
#### (5)RSA 私钥加密

加密指定字符串,并以指定编码格式输出结果

Expand All @@ -150,7 +151,7 @@ if err != nil {
fmt.Println("encrypt data :", encrypt)
```

#### (6)RSA公钥解密
#### (6)RSA 公钥解密

解密指定格式编码后的加密串,返回原字符串

Expand Down
10 changes: 4 additions & 6 deletions rsa/rsa.go
Original file line number Diff line number Diff line change
Expand Up @@ -229,8 +229,7 @@ func (rc *rsaCrypt) EncryptByPriKey(src string, outputDataType gocrypto.Encode)
}

output := bytes.NewBuffer(nil)
err = priKeyIO(prvKey, bytes.NewReader([]byte(src)), output, true)
if err != nil {
if err = priKeyIO(prvKey, bytes.NewReader([]byte(src)), output, true); err != nil {
return "", err
}

Expand Down Expand Up @@ -260,8 +259,7 @@ func (rc *rsaCrypt) DecryptByPublic(src string, srcType gocrypto.Encode) (dst st
}

output := bytes.NewBuffer(nil)
err = pubKeyIO(pubKey.(*rsa.PublicKey), bytes.NewReader(decodeData), output, false)
if err != nil {
if err = pubKeyIO(pubKey.(*rsa.PublicKey), bytes.NewReader(decodeData), output, false); err != nil {
return "", err
}
return output.String(), nil
Expand All @@ -285,13 +283,13 @@ func (rc *rsaCrypt) EncryptOAEP(src string, outputDataType gocrypto.Encode) (dst
if secretInfo.HashType > gocrypto.Sha512256 {
return "", errors.New("secretInfo HashType can't be supported")
}
hash, _ := gocrypto.GetHashFunc(secretInfo.HashType)

var (
srcBytes = []byte(src)
public = pubKey.(*rsa.PublicKey)
random = rand.Reader
msgLen = len(srcBytes)
hash, _ = gocrypto.GetHashFunc(secretInfo.HashType)
hashType = hash()
step = public.Size() - 2*hashType.Size() - 2
dataEncrypted []byte
Expand Down Expand Up @@ -336,9 +334,9 @@ func (rc *rsaCrypt) DecryptOAEP(src string, srcType gocrypto.Encode) (dst string
if secretInfo.HashType > gocrypto.Sha512256 {
return "", errors.New("secretInfo HashType can't be supported")
}
hash, _ := gocrypto.GetHashFunc(secretInfo.HashType)

var (
hash, _ = gocrypto.GetHashFunc(secretInfo.HashType)
random = rand.Reader
msgLen = len(decodeData)
step = private.PublicKey.Size()
Expand Down
13 changes: 5 additions & 8 deletions rsa/rsa_ext.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ func getPriKey(privateKey string, priType gocrypto.Encode, priKeyType gocrypto.S
return gocrypto.ParsePrivateKey(privateKeyDecoded, priKeyType)
}

// 公钥加密或解密byte
// 公钥加密或解密 byte
func pubKeyByte(pub *rsa.PublicKey, in []byte, isEncrypt bool) ([]byte, error) {
k := (pub.N.BitLen() + 7) / 8
if isEncrypt {
Expand All @@ -98,7 +98,7 @@ func pubKeyByte(pub *rsa.PublicKey, in []byte, isEncrypt bool) ([]byte, error) {
return io.ReadAll(out)
}

// 私钥加密或解密byte
// 私钥加密或解密 byte
func priKeyByte(pri *rsa.PrivateKey, in []byte, isEncrypt bool) ([]byte, error) {
k := (pri.N.BitLen() + 7) / 8
if isEncrypt {
Expand All @@ -121,7 +121,7 @@ func priKeyByte(pri *rsa.PrivateKey, in []byte, isEncrypt bool) ([]byte, error)
return io.ReadAll(out)
}

// 公钥加密或解密Reader
// 公钥加密或解密 Reader
func pubKeyIO(pub *rsa.PublicKey, in io.Reader, out io.Writer, isEncrypt bool) (err error) {
k := (pub.N.BitLen() + 7) / 8
if isEncrypt {
Expand Down Expand Up @@ -158,10 +158,9 @@ func pubKeyIO(pub *rsa.PublicKey, in io.Reader, out io.Writer, isEncrypt bool) (
return
}
}
return
}

// 私钥加密或解密Reader
// 私钥加密或解密 Reader
func priKeyIO(pri *rsa.PrivateKey, r io.Reader, w io.Writer, isEncrypt bool) (err error) {
k := (pri.N.BitLen() + 7) / 8
if isEncrypt {
Expand Down Expand Up @@ -198,7 +197,6 @@ func priKeyIO(pri *rsa.PrivateKey, r io.Reader, w io.Writer, isEncrypt bool) (er
return
}
}
return
}

// 公钥解密
Expand Down Expand Up @@ -342,8 +340,7 @@ func copyWithLeftPad(dest, src []byte) {

// 从crypto/rsa复制
func nonZeroRandomBytes(s []byte, rand io.Reader) (err error) {
_, err = io.ReadFull(rand, s)
if err != nil {
if _, err = io.ReadFull(rand, s); err != nil {
return
}
for i := 0; i < len(s); i++ {
Expand Down
6 changes: 3 additions & 3 deletions rsa/rsa_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ type testEncryptOAEPStruct struct {
}

func TestEncryptDecryptOAEP(t *testing.T) {
sha256 := sha256.New()
hash := sha256.New()
n := new(big.Int)
d := new(big.Int)
for i, test := range testEncryptOAEPData {
Expand All @@ -201,12 +201,12 @@ func TestEncryptDecryptOAEP(t *testing.T) {

for j, message := range test.msgs {
label := []byte(fmt.Sprintf("hi#%d", j))
enc, err := rsa.EncryptOAEP(sha256, rand.Reader, &priv.PublicKey, message.in, label)
enc, err := rsa.EncryptOAEP(hash, rand.Reader, &priv.PublicKey, message.in, label)
if err != nil {
t.Errorf("#%d,%d: EncryptOAEP: %v", i, j, err)
continue
}
dec, err := rsa.DecryptOAEP(sha256, rand.Reader, priv, enc, label)
dec, err := rsa.DecryptOAEP(hash, rand.Reader, priv, enc, label)
if err != nil {
t.Errorf("#%d,%d: DecryptOAEP: %v", i, j, err)
continue
Expand Down

0 comments on commit 02d12a0

Please sign in to comment.