Skip to content

Commit

Permalink
更新
Browse files Browse the repository at this point in the history
  • Loading branch information
deatil committed Oct 20, 2023
1 parent 1ffc5e7 commit ddd9abf
Show file tree
Hide file tree
Showing 21 changed files with 459 additions and 106 deletions.
144 changes: 117 additions & 27 deletions pkg/lakego-pkg/go-cryptobin/cryptobin/rsa/rsa_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,37 +2,14 @@ package rsa

import (
"testing"
"reflect"
)

func assertT(t *testing.T) func(any, any, string) {
return func(actual any, expected any, msg string) {
if !reflect.DeepEqual(actual, expected) {
t.Errorf("Failed %s: actual: %v, expected: %v", msg, actual, expected)
}
}
}

func assertErrorT(t *testing.T) func(error, string) {
return func(err error, msg string) {
if err != nil {
t.Errorf("Failed %s: error: %+v", msg, err)
}
}
}

func AssertNotEmptyT(t *testing.T) func(string, string) {
return func(data string, msg string) {
if data == "" {
t.Errorf("Failed %s: error: data empty", msg)
}
}
}
cryptobin_test "github.com/deatil/go-cryptobin/tool/test"
)

// Test_PrimeKeyGeneration
func Test_PrimeKeyGeneration(t *testing.T) {
assertNotEmpty := AssertNotEmptyT(t)
assertError := assertErrorT(t)
assertNotEmpty := cryptobin_test.AssertNotEmptyT(t)
assertError := cryptobin_test.AssertErrorT(t)

size := 768
if testing.Short() {
Expand All @@ -51,3 +28,116 @@ func Test_PrimeKeyGeneration(t *testing.T) {
assertError(objPubKey.Error(), "objPubKey")
assertNotEmpty(objPubKey.ToKeyString(), "objPubKey")
}

var (
testSignPrikeyPkcs1En = `
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-256-CBC,c47d6aef98e01776d8519936adb449ad
2YSwbFUmWFWYlMLtkCWI2B8k8WxcmSyuu4vhLcHZrsIYm0EIe3xX7AkfXodZgO1g
vjjbX4w/qaB3WPg4Re9TxgaLqEEY0DRkuP4m/kDsu40ZQyMlGrXKl3Yp8D6Te2Wf
RcRBgibWwNJVgZYQ6nY/82SA2gIcvCQVo0VZVQQ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POg/0RutacEoB2BUvHxPu+RJZoj/3K2nvLtPJo5wWLBQW4F3TdPSn79VlGaWN
gTDY21sYPVz+5kIl3RSnPWwpOCUw23ZNGaHVX4xtnVzzBkC1cJeGeaBgZjht5uf1
wuh57g/neLBzjBUHKxAs3OdDUKYejg/HFrId0f+nDCuRwoJeyEwxkt7fJizIFftH
9Ks42I5ndTcB7zs1Eb5IF/HYYWHTzNLRm+Wt57LyoG++nOv0kMmlHiX9omgtsveA
Y6ONUeTxWwa2ljP5zpslGXYhmVyRg6hC/LnoqfUFf2jV5m+epvOOSQgQkzIrxN9j
QTquQhzUaaKpTBPPvkIHSb6568PLvhHqx/ilDGvp9UAWtO6bfXGwOIZcL3p9WetE
2sasOjp/VhgUJD37a0G7pwZpAoLsNC+tEUtaFkw5nNLMFM0urGYHBsVNZt/N2ibM
gKkq5AB/Zv4foXuqxsZM3k6V1uDpesQXt+/Xnqysi9MQkk16r+N9+uctugReej8M
nPaPvK54bnJ7HA9fnKt1Vf+x/NLGLdIX4xIzqBC4xOqLQlTbStRw2XRDGespR376
JnsP82g2PQN+dH0QNbW/C/eq5mfpAxh6x8JFBaha7/33czh465yg7Qpos+AMGK/D
TYEOgSzqZlhf5ISMB5uAwOW6k4TuJAUbrA==
-----END ENCRYPTED PRIVATE KEY-----
`

testSignPubkey = `
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDbvgUxbNl35YrbZDPCVYOdJSxX
j69JLx3LwRUfGj34BdMb/DJuuoDzVA+fppISMul9mNaspHxguWsHgnvSpc4Swceq
t5Rr4E4VBnudvTe7BU9aHmbY4g7aldJ+S5gC3dT11wHz6Sre+2a74xsZxs51+M0Q
tGjMoEruLNj7fkPcNQIDAQAB
-----END PUBLIC KEY-----
`
)

func Test_RSAPkcs1Sign(t *testing.T) {
assertNotEmpty := cryptobin_test.AssertNotEmptyT(t)
assertError := cryptobin_test.AssertErrorT(t)
assertTrue := cryptobin_test.AssertTrueT(t)

data := "test-pass"

obj := NewRsa()

sign := obj.
FromString(data).
FromPKCS1PrivateKeyWithPassword([]byte(testSignPrikeyPkcs1En), "123").
SetSignHash("SHA256").
Sign()
signData := sign.ToBase64String()

assertError(sign.Error(), "RSAPkcs1Sign-sign")
assertNotEmpty(signData, "RSAPkcs1Sign-sign")

verify := obj.
FromBase64String(signData).
FromPublicKey([]byte(testSignPubkey)).
SetSignHash("SHA256").
Verify([]byte(data))
verifyData := verify.ToVerify()

assertError(verify.Error(), "RSAPkcs1Sign-verify")
assertTrue(verifyData, "RSAPkcs1Sign-verify")
}

func Test_RSAPkcs8Sign(t *testing.T) {
assertNotEmpty := cryptobin_test.AssertNotEmptyT(t)
assertError := cryptobin_test.AssertErrorT(t)
assertTrue := cryptobin_test.AssertTrueT(t)

data := "test-pass22222"

obj := NewRsa()

sign := obj.
FromString(data).
FromPKCS8PrivateKeyWithPassword([]byte(testSignPrikeyPkcs8En), "123").
SetSignHash("SHA256").
Sign()
signData := sign.ToBase64String()

assertError(sign.Error(), "RSAPkcs1Sign-sign")
assertNotEmpty(signData, "RSAPkcs1Sign-sign")

verify := obj.
FromBase64String(signData).
FromPublicKey([]byte(testSignPubkey)).
SetSignHash("SHA256").
Verify([]byte(data))
verifyData := verify.ToVerify()

assertError(verify.Error(), "RSAPkcs1Sign-verify")
assertTrue(verifyData, "RSAPkcs1Sign-verify")
}
56 changes: 43 additions & 13 deletions pkg/lakego-pkg/go-cryptobin/cryptobin/sm2/encryption.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package sm2

import (
"io"
"errors"
"crypto/rand"

Expand All @@ -15,7 +14,7 @@ func (this SM2) Encrypt() SM2 {
return this.AppendError(err)
}

paredData, err := this.EncryptAsn1(this.publicKey, this.data, this.mode, rand.Reader)
paredData, err := sm2.Encrypt(this.publicKey, this.data, rand.Reader, this.mode)
if err != nil {
return this.AppendError(err)
}
Expand All @@ -32,7 +31,7 @@ func (this SM2) Decrypt() SM2 {
return this.AppendError(err)
}

paredData, err := this.DecryptAsn1(this.privateKey, this.data, this.mode)
paredData, err := sm2.Decrypt(this.privateKey, this.data, this.mode)
if err != nil {
return this.AppendError(err)
}
Expand All @@ -42,22 +41,53 @@ func (this SM2) Decrypt() SM2 {
return this
}

// sm2 加密,返回 asn.1 编码格式的密文内容
func (this SM2) EncryptAsn1(pub *sm2.PublicKey, data []byte, mode int, rand io.Reader) ([]byte, error) {
cipher, err := sm2.Encrypt(pub, data, rand, mode)
// ================

// 公钥加密,返回 asn.1 编码格式的密文内容
func (this SM2) EncryptAsn1() SM2 {
data, err := sm2.Encrypt(this.publicKey, this.data, rand.Reader, this.mode)
if err != nil {
return this.AppendError(err)
}

var paredData []byte

if this.mode == C1C2C3 {
paredData, err = cipherC1C2C3Marshal(data)
} else {
paredData, err = sm2.CipherMarshal(data)
}

if err != nil {
return nil, err
return this.AppendError(err)
}

return sm2.CipherMarshal(cipher)
this.paredData = paredData

return this
}

// sm2 解密,解析 asn.1 编码格式的密文内容
func (this SM2) DecryptAsn1(pub *sm2.PrivateKey, data []byte, mode int) ([]byte, error) {
cipher, err := sm2.CipherUnmarshal(data)
// 私钥解密,解析 asn.1 编码格式的密文内容
func (this SM2) DecryptAsn1() SM2 {
var data []byte
var err error

if this.mode == C1C2C3 {
data, err = cipherC1C2C3Unmarshal(this.data)
} else {
data, err = sm2.CipherUnmarshal(this.data)
}

if err != nil {
return nil, err
return this.AppendError(err)
}

return sm2.Decrypt(pub, cipher, mode)
paredData, err := sm2.Decrypt(this.privateKey, data, this.mode)
if err != nil {
return this.AppendError(err)
}

this.paredData = paredData

return this
}
34 changes: 17 additions & 17 deletions pkg/lakego-pkg/go-cryptobin/cryptobin/sm2/from.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ func GenerateKey() SM2 {
return defaultSM2.GenerateKey()
}

// 使用数据生成密钥对
// 使用自定义数据生成密钥对
func (this SM2) GenerateKeyWithSeed(reader io.Reader) SM2 {
privateKey, err := sm2.GenerateKey(reader)
if err != nil {
Expand All @@ -47,7 +47,7 @@ func (this SM2) GenerateKeyWithSeed(reader io.Reader) SM2 {
return this
}

// 使用数据生成密钥对
// 使用自定义数据生成密钥对
func GenerateKeyWithSeed(reader io.Reader) SM2 {
return defaultSM2.GenerateKeyWithSeed(reader)
}
Expand Down Expand Up @@ -265,7 +265,7 @@ func (this SM2) FromPublicKeyXYString(xString, yString string) SM2 {
return this
}

// 公钥字符对
// 公钥 x,y 字节对
func (this SM2) FromPublicKeyXYBytes(XBytes, YBytes []byte) SM2 {
x := new(big.Int).SetBytes(XBytes)
y := new(big.Int).SetBytes(YBytes)
Expand All @@ -281,7 +281,7 @@ func (this SM2) FromPublicKeyXYBytes(XBytes, YBytes []byte) SM2 {

// ==========

// 公钥未压缩字符 (hexStringX + hexStringY)
// 公钥明文未压缩 (hexStringX + hexStringY)
// public-key: 047c********.
func (this SM2) FromPublicKeyUncompressString(keyString string) SM2 {
if len(keyString) == 130 && strings.HasPrefix(keyString, "04") {
Expand All @@ -300,7 +300,7 @@ func (this SM2) FromPublicKeyUncompressString(keyString string) SM2 {
return this
}

// 公钥压缩
// 公钥明文压缩
// public-key: 027c******** || 036c********
// 0333B01B61D94A775DA72A0BFF9AB324DE672EA0977584D23AF34F8150223305B0
// 023613B13F252F6FB2374A85D93C7FFE9CCAD1231BE866F5FE69255312CE85B9FF
Expand All @@ -310,17 +310,17 @@ func (this SM2) FromPublicKeyCompressString(key string) SM2 {
return this.AppendError(err)
}

pre := formatFromPublicKeyCompressPrefix(key[:2])
key = pre + key[2:]

d, _ := new(big.Int).SetString(key[:], 16)

this.publicKey = sm2.Decompress(d.Bytes())
y := d.Bytes()
y[0] &= 1

this.publicKey = sm2.Decompress(y)

return this
}

// 公钥
// 公钥明文
func (this SM2) FromPublicKeyString(key string) SM2 {
if len(key) == 66 {
return this.FromPublicKeyCompressString(key)
Expand All @@ -329,7 +329,7 @@ func (this SM2) FromPublicKeyString(key string) SM2 {
return this.FromPublicKeyUncompressString(key)
}

// 私钥字符,必须先添加公钥 (hexStringD)
// 私钥明文
// private-key: 07e4********;
func (this SM2) FromPrivateKeyString(keyString string) SM2 {
c := sm2.P256Sm2()
Expand All @@ -347,14 +347,14 @@ func (this SM2) FromPrivateKeyString(keyString string) SM2 {

// ==========

// 公钥压缩字节, hex 或者 base64 解码后
// 公钥明文, hex 或者 base64 解码后
func (this SM2) FromPublicKeyBytes(pubBytes []byte) SM2 {
key := cryptobin_tool.HexEncode(pubBytes)

return this.FromPublicKeyString(key)
}

// 明文私钥生成私钥结构体, hex 或者 base64 解码后
// 私钥明文, hex 或者 base64 解码后
func (this SM2) FromPrivateKeyBytes(priBytes []byte) SM2 {
c := sm2.P256Sm2()
k := new(big.Int).SetBytes(priBytes)
Expand Down Expand Up @@ -395,7 +395,7 @@ func FromString(data string) SM2 {
return defaultSM2.FromString(data)
}

// Base64
// Base64数据
func (this SM2) FromBase64String(data string) SM2 {
newData, err := cryptobin_tool.Base64Decode(data)
if err != nil {
Expand All @@ -407,12 +407,12 @@ func (this SM2) FromBase64String(data string) SM2 {
return this
}

// Base64
// Base64数据
func FromBase64String(data string) SM2 {
return defaultSM2.FromBase64String(data)
}

// Hex
// 16进制数据
func (this SM2) FromHexString(data string) SM2 {
newData, err := cryptobin_tool.HexDecode(data)
if err != nil {
Expand All @@ -424,7 +424,7 @@ func (this SM2) FromHexString(data string) SM2 {
return this
}

// Hex
// 16进制数据
func FromHexString(data string) SM2 {
return defaultSM2.FromHexString(data)
}
5 changes: 2 additions & 3 deletions pkg/lakego-pkg/go-cryptobin/cryptobin/sm2/get.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,12 +76,11 @@ func (this SM2) GetPublicKeyUncompressString() string {
// 获取压缩公钥
func (this SM2) GetPublicKeyCompressString() string {
data := sm2.Compress(this.publicKey)
data[0] = 2 | (this.publicKey.Y.Bytes()[sm2p256ElementLength-1] & 1)

dataHex := cryptobin_tool.HexEncode(data)

pre := formatPublicKeyCompressPrefix(dataHex[:2])

return pre + dataHex[2:]
return dataHex
}

// 获取 keyData
Expand Down
2 changes: 2 additions & 0 deletions pkg/lakego-pkg/go-cryptobin/cryptobin/sm2/sm2.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"github.com/tjfoc/gmsm/sm2"
)

const sm2p256ElementLength = 32

var (
// 类型
C1C3C2 = sm2.C1C3C2
Expand Down
Loading

0 comments on commit ddd9abf

Please sign in to comment.