Commit 58871f6c authored by pengjun's avatar pengjun

update sdk

parent f0eaf0fc
package sdk package sdk
import ( import (
"errors"
"gitlab.33.cn/pengjun/reencrypt/sdk/crypto" "gitlab.33.cn/pengjun/reencrypt/sdk/crypto"
) )
...@@ -13,21 +14,27 @@ type Account struct { ...@@ -13,21 +14,27 @@ type Account struct {
func NewAccount(signType string) (*Account, error) { func NewAccount(signType string) (*Account, error) {
if signType == "" { if signType == "" {
signType = crypto.SECP256k1 signType = crypto.SECP256K1
} }
account := Account{} account := Account{}
account.SignType = signType account.SignType = signType
if signType == crypto.SECP256K1 {
account.PrivateKey = crypto.GeneratePrivateKey()
account.PublicKey = crypto.PubKeyFromPrivate(account.PrivateKey)
driver := crypto.NewSignDriver(signType) addr, err := crypto.PubKeyToAddress(account.PublicKey)
account.PrivateKey = driver.GeneratePrivateKey() if err != nil {
account.PublicKey = driver.PubKeyFromPrivate(account.PrivateKey) return nil, err
}
addr, err := crypto.PubKeyToAddress(account.PublicKey) account.Address = addr
if err != nil { } else if signType == crypto.SM2 {
return nil, err // TODO
} else if signType == crypto.ED25519 {
// TODO
} else {
return nil, errors.New("sign type not support")
} }
account.Address = addr
return &account, nil return &account, nil
} }
\ No newline at end of file
...@@ -12,6 +12,7 @@ import ( ...@@ -12,6 +12,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"github.com/golang/protobuf/proto" "github.com/golang/protobuf/proto"
"io/ioutil" "io/ioutil"
"net/http" "net/http"
"strings" "strings"
...@@ -119,12 +120,53 @@ func (client *JSONClient) Call(method string, params, resp interface{}) error { ...@@ -119,12 +120,53 @@ func (client *JSONClient) Call(method string, params, resp interface{}) error {
return json.Unmarshal(*cresp.Result, resp) return json.Unmarshal(*cresp.Result, resp)
} }
type ParseFunc func(result json.RawMessage) (interface{},error)
//回调函数,用于自定义解析返回得result数据
func (client *JSONClient) CallBack(method string, params interface{},parseFunc ParseFunc) (interface{}, error) {
method = addPrefix(client.prefix, method)
req := &clientRequest{}
req.Method = method
req.Params[0] = params
data, err := json.Marshal(req)
if err != nil {
return nil, err
}
postresp, err := client.client.Post(client.url, "application/json", bytes.NewBuffer(data))
if err != nil {
return nil, err
}
defer postresp.Body.Close()
b, err := ioutil.ReadAll(postresp.Body)
if err != nil {
return nil, err
}
cresp := &clientResponse{}
err = json.Unmarshal(b, &cresp)
if err != nil {
return nil, err
}
if cresp.Error != nil {
x, ok := cresp.Error.(string)
if !ok {
return nil, fmt.Errorf("invalid error %v", cresp.Error)
}
if x == "" {
x = "unspecified error"
}
return nil, fmt.Errorf(x)
}
if cresp.Result == nil {
return nil, errors.New("Empty result")
}
return parseFunc(*cresp.Result)
}
// 发送交易 // 发送交易
func (client *JSONClient) SendTransaction(signedTx string) (string, error) { func (client *JSONClient) SendTransaction(signedTx string) (string, error) {
var res string var res string
send := &RawParm{ send := &RawParm{
Token: "BTY", Token: "BTY",
Data: signedTx, Data: signedTx,
} }
err := client.Call("Chain33.SendTransaction", send, &res) err := client.Call("Chain33.SendTransaction", send, &res)
if err != nil { if err != nil {
...@@ -146,4 +188,4 @@ func (client *JSONClient) QueryTransaction(hash string) (*TransactionDetail, err ...@@ -146,4 +188,4 @@ func (client *JSONClient) QueryTransaction(hash string) (*TransactionDetail, err
} }
return &detail, nil return &detail, nil
} }
\ No newline at end of file
...@@ -91,3 +91,10 @@ type TransactionDetail struct { ...@@ -91,3 +91,10 @@ type TransactionDetail struct {
TxProofs []*TxProof `json:"txProofs"` TxProofs []*TxProof `json:"txProofs"`
FullHash string `json:"fullHash"` FullHash string `json:"fullHash"`
} }
// Query4Jrpc query jrpc
type Query4Jrpc struct {
Execer string `json:"execer"`
FuncName string `json:"funcName"`
Payload json.RawMessage `json:"payload"`
}
...@@ -4,7 +4,6 @@ import ( ...@@ -4,7 +4,6 @@ import (
"crypto/sha256" "crypto/sha256"
"fmt" "fmt"
"github.com/mr-tron/base58/base58" "github.com/mr-tron/base58/base58"
"golang.org/x/crypto/ripemd160"
) )
//不同币种的前缀版本号 //不同币种的前缀版本号
...@@ -17,24 +16,18 @@ var coinPrefix = map[string][]byte{ ...@@ -17,24 +16,18 @@ var coinPrefix = map[string][]byte{
"USDT": {0x00}, "USDT": {0x00},
} }
var addrSeed = []byte("address seed bytes for public key")
//MaxExecNameLength 执行器名最大长度
const MaxExecNameLength = 100
func PubKeyToAddress(pub []byte) (addr string, err error) { func PubKeyToAddress(pub []byte) (addr string, err error) {
if len(pub) != 33 && len(pub) != 65 { //压缩格式 与 非压缩格式 if len(pub) != 33 && len(pub) != 65 { //压缩格式 与 非压缩格式
return "", fmt.Errorf("invalid public key byte") return "", fmt.Errorf("invalid public key byte")
} }
sha256h := sha256.New()
_, err = sha256h.Write(pub)
if err != nil {
return "", err
}
//160hash
ripemd160h := ripemd160.New()
_, err = ripemd160h.Write(sha256h.Sum([]byte("")))
if err != nil {
return "", err
}
//添加版本号 //添加版本号
hash160res := append(coinPrefix["BTY"], ripemd160h.Sum([]byte(""))...) hash160res := append(coinPrefix["BTY"], Rimp160(pub)...)
//添加校验码 //添加校验码
cksum := checksum(hash160res) cksum := checksum(hash160res)
...@@ -61,4 +54,27 @@ func checksum(input []byte) (cksum [4]byte) { ...@@ -61,4 +54,27 @@ func checksum(input []byte) (cksum [4]byte) {
finalHash := h.Sum(nil) finalHash := h.Sum(nil)
copy(cksum[:], finalHash[:]) copy(cksum[:], finalHash[:])
return return
}
func GetExecAddress(name string) string {
if len(name) > MaxExecNameLength {
panic("name too long")
}
var bname [200]byte
buf := append(bname[:0], addrSeed...)
buf = append(buf, []byte(name)...)
pub := Sha2Sum(buf)
var ad [25]byte
ad[0] = 0
copy(ad[1:21], Rimp160(pub))
sh := Sha2Sum(ad[0:21])
checksum := make([]byte, 4)
copy(checksum, sh[:4])
copy(ad[21:25], checksum[:])
addr := base58.Encode(ad[:])
return addr
} }
\ No newline at end of file
...@@ -9,6 +9,10 @@ import ( ...@@ -9,6 +9,10 @@ import (
"io" "io"
) )
const (
AESPrivateKeyLength = 16
)
func pkcs7Padding(src []byte) []byte { func pkcs7Padding(src []byte) []byte {
padding := aes.BlockSize - len(src)%aes.BlockSize padding := aes.BlockSize - len(src)%aes.BlockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding) padtext := bytes.Repeat([]byte{byte(padding)}, padding)
...@@ -94,4 +98,8 @@ func AESCBCPKCS7Decrypt(key, src []byte) ([]byte, error) { ...@@ -94,4 +98,8 @@ func AESCBCPKCS7Decrypt(key, src []byte) ([]byte, error) {
return pkcs7UnPadding(pt) return pkcs7UnPadding(pt)
} }
return nil, err return nil, err
}
func GenetateAESKey() []byte {
return getRandBytes(AESPrivateKeyLength)
} }
\ No newline at end of file
package crypto package crypto
import ( import (
"bytes"
"crypto/rand" "crypto/rand"
"crypto/sha256"
secp256k1 "github.com/btcsuite/btcd/btcec" secp256k1 "github.com/btcsuite/btcd/btcec"
) )
var ( var (
SECP256k1 = "secp256k1" SECP256K1 = "secp256k1"
SM2 = "sm2" //TODO SM2 = "sm2"
ED25519 = "ed25519" //TODO ED25519 = "ed25519" //TODO
) )
type CryptoDriver interface { func GeneratePrivateKey() []byte {
GeneratePrivateKey() []byte privKeyBytes := make([]byte, 32)
PubKeyFromPrivate(privKey []byte) []byte for {
Sign(msg []byte, privKey []byte) []byte key := getRandBytes(32)
} if bytes.Compare(key, secp256k1.S256().Params().N.Bytes()) >= 0 {
continue
func NewSignDriver(signType string) CryptoDriver { }
if signType == "secp256k1"{ copy(privKeyBytes[:], key)
return &Secp256k1Driver{} break
} else {
// TODO
return nil
} }
}
type Secp256k1Driver struct { }
func (driver *Secp256k1Driver) GeneratePrivateKey() []byte {
privKeyBytes := make([]byte, 32)
copy(privKeyBytes[:], GetRandBytes(32))
priv, _ := secp256k1.PrivKeyFromBytes(secp256k1.S256(), privKeyBytes[:]) priv, _ := secp256k1.PrivKeyFromBytes(secp256k1.S256(), privKeyBytes[:])
copy(privKeyBytes[:], priv.Serialize()) copy(privKeyBytes[:], priv.Serialize())
return privKeyBytes return privKeyBytes
} }
func (driver *Secp256k1Driver) PubKeyFromPrivate(privKey []byte) []byte { func PubKeyFromPrivate(privKey []byte) []byte {
_, pub := secp256k1.PrivKeyFromBytes(secp256k1.S256(), privKey[:]) _, pub := secp256k1.PrivKeyFromBytes(secp256k1.S256(), privKey[:])
pubSecp256k1 := make([]byte, 33) pubSecp256k1 := make([]byte, 33)
copy(pubSecp256k1[:], pub.SerializeCompressed()) copy(pubSecp256k1[:], pub.SerializeCompressed())
return pubSecp256k1 return pubSecp256k1
} }
func (driver *Secp256k1Driver) Sign(msg []byte, privKey []byte) []byte { func Sign(msg []byte, privKey []byte) []byte {
priv, _ := secp256k1.PrivKeyFromBytes(secp256k1.S256(), privKey[:]) priv, _ := secp256k1.PrivKeyFromBytes(secp256k1.S256(), privKey[:])
sig, err := priv.Sign(Sha256(msg)) sig, err := priv.Sign(Sha256(msg))
if err != nil { if err != nil {
...@@ -52,27 +44,21 @@ func (driver *Secp256k1Driver) Sign(msg []byte, privKey []byte) []byte { ...@@ -52,27 +44,21 @@ func (driver *Secp256k1Driver) Sign(msg []byte, privKey []byte) []byte {
return sig.Serialize() return sig.Serialize()
} }
func PrivateECDSAFromByte(privKey []byte) *secp256k1.PrivateKey { func PrivateFromByte(privKey []byte) *secp256k1.PrivateKey {
priv, _ := secp256k1.PrivKeyFromBytes(secp256k1.S256(), privKey[:]) priv, _ := secp256k1.PrivKeyFromBytes(secp256k1.S256(), privKey[:])
return priv return priv
} }
func PublicECDSAFromByte(pubKey []byte) *secp256k1.PublicKey { func PublicFromByte(pubKey []byte) *secp256k1.PublicKey {
pub, _ := secp256k1.ParsePubKey(pubKey, secp256k1.S256()) pub, _ := secp256k1.ParsePubKey(pubKey, secp256k1.S256())
return pub return pub
} }
func GetRandBytes(numBytes int) []byte { func getRandBytes(numBytes int) []byte {
b := make([]byte, numBytes) b := make([]byte, numBytes)
_, err := rand.Read(b) _, err := rand.Read(b)
if err != nil { if err != nil {
panic("Panic on a Crisis" + err.Error()) panic("Panic on a Crisis" + err.Error())
} }
return b return b
} }
\ No newline at end of file
func Sha256(b []byte) []byte {
hasher := sha256.New()
hasher.Write(b)
return hasher.Sum(nil)
}
...@@ -2,12 +2,15 @@ package crypto ...@@ -2,12 +2,15 @@ package crypto
import ( import (
"fmt" "fmt"
"github.com/33cn/chain33-sdk-go/crypto/gm"
"github.com/33cn/chain33-sdk-go/types"
"github.com/stretchr/testify/assert"
"testing" "testing"
) )
func TestAES(t *testing.T) { func TestAES(t *testing.T) {
var text = "hello aes" var text = "hello aes"
var key = GetRandBytes(32) var key = getRandBytes(16)
cipherText, err := AESCBCPKCS7Encrypt(key, []byte(text)) cipherText, err := AESCBCPKCS7Encrypt(key, []byte(text))
if err != nil { if err != nil {
...@@ -21,5 +24,63 @@ func TestAES(t *testing.T) { ...@@ -21,5 +24,63 @@ func TestAES(t *testing.T) {
return return
} }
fmt.Println(string(cipher)) assert.Equal(t, text, string(cipher))
}
func TestSign(t *testing.T) {
priv, _ := types.FromHex("0xc2b31057b8692a56c7dd18199df71c1d21b781c0b6858c52997c9dbf778e8550")
msg := []byte("sign test")
sig := Sign(msg, priv)
fmt.Printf("sig = %x\n", sig)
}
func TestSM2(t *testing.T) {
priv, pub := gm.GenetateKey()
fmt.Println(types.ToHex(pub))
msg := []byte("sign test")
sig := gm.SM2Sign(msg, priv, nil)
fmt.Printf("sig = %x\n", sig)
result := gm.SM2Verify(msg, pub, sig, nil)
fmt.Println(result)
}
func TestSM4(t *testing.T) {
key := []byte{0x1, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10}
fmt.Printf("key = %v\n", key)
data := []byte{0x1, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10}
fmt.Printf("data = %x\n", data)
d0 := gm.SM4Encrypt(key, data)
fmt.Printf("d0 = %x\n", d0)
d1 := gm.SM4Decrypt(key, d0)
fmt.Printf("d1 = %x\n", d1)
assert.Equal(t, data, d1)
}
func TestAddress(t *testing.T) {
priv, _ := types.FromHex("0xc2b31057b8692a56c7dd18199df71c1d21b781c0b6858c52997c9dbf778e8550")
pub := PubKeyFromPrivate(priv)
fmt.Println(types.ToHex(pub))
addr, err := PubKeyToAddress(pub)
if err != nil {
panic(err)
}
fmt.Println(addr)
}
func TestKDF(t *testing.T) {
key := []byte{0x1, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10, 0x11}
keyf := KDF(key, 32)
fmt.Println(keyf)
fmt.Println(len(keyf))
} }
package crypto
import (
"crypto/sha256"
"golang.org/x/crypto/ripemd160"
"math/big"
)
func Sha256(b []byte) []byte {
hasher := sha256.New()
hasher.Write(b)
return hasher.Sum(nil)
}
func Sha2Sum(b []byte) []byte {
tmp := sha256.Sum256(b)
tmp = sha256.Sum256(tmp[:])
return tmp[:]
}
func rimpHash(in []byte, out []byte) {
sha := sha256.New()
_, err := sha.Write(in)
if err != nil {
return
}
rim := ripemd160.New()
_, err = rim.Write(sha.Sum(nil)[:])
if err != nil {
return
}
copy(out, rim.Sum(nil))
}
// Rimp160 Returns hash: RIMP160( SHA256( data ) )
// Where possible, using RimpHash() should be a bit faster
func Rimp160(b []byte) []byte {
out := make([]byte, 20)
rimpHash(b, out[:])
return out[:]
}
func KDF(x []byte, length int) []byte {
var c []byte
var ct int64 = 1
h := sha256.New()
for i, j := 0, (length+31)/32; i < j; i++ {
h.Reset()
h.Write(x)
h.Write(big.NewInt(ct).Bytes())
hash := h.Sum(nil)
if i+1 == j && length%32 != 0 {
c = append(c, hash[:length%32]...)
} else {
c = append(c, hash...)
}
ct++
}
return c
}
\ No newline at end of file
...@@ -7,7 +7,6 @@ import ( ...@@ -7,7 +7,6 @@ import (
secp256k1 "github.com/btcsuite/btcd/btcec" secp256k1 "github.com/btcsuite/btcd/btcec"
"gitlab.33.cn/pengjun/reencrypt/sdk/crypto" "gitlab.33.cn/pengjun/reencrypt/sdk/crypto"
"gitlab.33.cn/pengjun/reencrypt/sdk/types" "gitlab.33.cn/pengjun/reencrypt/sdk/types"
"golang.org/x/crypto/blake2b" "golang.org/x/crypto/blake2b"
"math/big" "math/big"
) )
...@@ -38,7 +37,7 @@ func NewEccPoint(pubStr string) (*EccPoit, error) { ...@@ -38,7 +37,7 @@ func NewEccPoint(pubStr string) (*EccPoit, error) {
fmt.Errorf("get reKeyRByte err", err) fmt.Errorf("get reKeyRByte err", err)
return nil, err return nil, err
} }
reKeyR := crypto.PublicECDSAFromByte(reKeyRByte) reKeyR := crypto.PublicFromByte(reKeyRByte)
return &EccPoit{x: reKeyR.X, y: reKeyR.Y}, nil return &EccPoit{x: reKeyR.X, y: reKeyR.Y}, nil
} }
...@@ -67,23 +66,24 @@ func (p *EccPoit) ToPublicKey() *secp256k1.PublicKey { ...@@ -67,23 +66,24 @@ func (p *EccPoit) ToPublicKey() *secp256k1.PublicKey {
} }
func hashToModInt(digest []byte) *big.Int { func hashToModInt(digest []byte) *big.Int {
sum := new(big.Int).SetBytes(digest) orderBits := baseN.BitLen()
one := big.NewInt(1) orderBytes := (orderBits + 7) / 8
order_minus_1 := big.NewInt(0) if len(digest) > orderBytes {
order_minus_1.Sub(baseN, one) digest = digest[:orderBytes]
}
bigNum := big.NewInt(0)
bigNum.Mod(sum, order_minus_1).Add(bigNum, one)
return bigNum ret := new(big.Int).SetBytes(digest)
excess := len(digest)*8 - orderBits
if excess > 0 {
ret.Rsh(ret, uint(excess))
}
return ret
} }
func makeShamirPolyCoeff(threshold int) []*big.Int { func makeShamirPolyCoeff(threshold int) []*big.Int {
driver := crypto.NewSignDriver(crypto.SECP256k1)
coeffs := make([]*big.Int, threshold-1) coeffs := make([]*big.Int, threshold-1)
for i,_ := range coeffs { for i,_ := range coeffs {
key := crypto.PrivateECDSAFromByte(driver.GeneratePrivateKey()) coeffs[i] = new(big.Int).SetBytes(crypto.GeneratePrivateKey())
coeffs[i] = key.D
} }
return coeffs return coeffs
...@@ -140,12 +140,11 @@ func getRandomInt(order *big.Int) *big.Int { ...@@ -140,12 +140,11 @@ func getRandomInt(order *big.Int) *big.Int {
return randInt return randInt
} }
func GenerateEncryptKey(pubOwner []byte) ([]byte, string, string) { func GeneratePreEncryptKey(pubOwner []byte) ([]byte, string, string) {
pubOwnerKey := crypto.PublicECDSAFromByte(pubOwner) pubOwnerKey := crypto.PublicFromByte(pubOwner)
driver := crypto.NewSignDriver(crypto.SECP256k1) priv_r := crypto.PrivateFromByte(crypto.GeneratePrivateKey())
priv_r := crypto.PrivateECDSAFromByte(driver.GeneratePrivateKey()) priv_u := crypto.PrivateFromByte(crypto.GeneratePrivateKey())
priv_u := crypto.PrivateECDSAFromByte(driver.GeneratePrivateKey())
result := &secp256k1.PublicKey{} result := &secp256k1.PublicKey{}
result.Curve = pubOwnerKey.Curve result.Curve = pubOwnerKey.Curve
...@@ -156,16 +155,16 @@ func GenerateEncryptKey(pubOwner []byte) ([]byte, string, string) { ...@@ -156,16 +155,16 @@ func GenerateEncryptKey(pubOwner []byte) ([]byte, string, string) {
pub_r := types.ToHex((*secp256k1.PublicKey)(&priv_r.PublicKey).SerializeCompressed()) pub_r := types.ToHex((*secp256k1.PublicKey)(&priv_r.PublicKey).SerializeCompressed())
pub_u := types.ToHex((*secp256k1.PublicKey)(&priv_u.PublicKey).SerializeCompressed()) pub_u := types.ToHex((*secp256k1.PublicKey)(&priv_u.PublicKey).SerializeCompressed())
return result.SerializeCompressed(), pub_r, pub_u share_key := crypto.KDF(result.SerializeCompressed(), 32)
return share_key, pub_r, pub_u
} }
func GenerateKeyFragments(privOwner []byte, pubRecipient []byte, numSplit, threshold int) ([]*KFrag, error) { func GenerateKeyFragments(privOwner []byte, pubRecipient []byte, numSplit, threshold int) ([]*KFrag, error) {
driver := crypto.NewSignDriver(crypto.SECP256k1) precursor := crypto.PrivateFromByte(crypto.GeneratePrivateKey())
precursor := crypto.PrivateECDSAFromByte(driver.GeneratePrivateKey())
precurPub := types.ToHex((*secp256k1.PublicKey)(&precursor.PublicKey).SerializeCompressed()) precurPub := types.ToHex((*secp256k1.PublicKey)(&precursor.PublicKey).SerializeCompressed())
privOwnerKey := crypto.PrivateECDSAFromByte(privOwner) privOwnerKey := crypto.PrivateFromByte(privOwner)
pubRecipientKey := crypto.PublicECDSAFromByte(pubRecipient) pubRecipientKey := crypto.PublicFromByte(pubRecipient)
dh_Alice_poit_x := types.ECDH(precursor, pubRecipientKey) dh_Alice_poit_x := types.ECDH(precursor, pubRecipientKey)
dAliceHash, err := blake2b.New256(precursor.X.Bytes()) dAliceHash, err := blake2b.New256(precursor.X.Bytes())
...@@ -211,13 +210,13 @@ func GenerateKeyFragments(privOwner []byte, pubRecipient []byte, numSplit, thres ...@@ -211,13 +210,13 @@ func GenerateKeyFragments(privOwner []byte, pubRecipient []byte, numSplit, thres
} }
func AssembleReencryptFragment(privRecipient []byte, reKeyFrags []*ReKeyFrag) ([]byte, error) { func AssembleReencryptFragment(privRecipient []byte, reKeyFrags []*ReKeyFrag) ([]byte, error) {
privRecipientKey := crypto.PrivateECDSAFromByte(privRecipient) privRecipientKey := crypto.PrivateFromByte(privRecipient)
precursor, err := types.FromHex(reKeyFrags[0].PrecurPub) precursor, err := types.FromHex(reKeyFrags[0].PrecurPub)
if err != nil { if err != nil {
fmt.Errorf("FromHex", err) fmt.Errorf("FromHex", err)
return nil, err return nil, err
} }
precursorPubKey := crypto.PublicECDSAFromByte(precursor) precursorPubKey := crypto.PublicFromByte(precursor)
dh_Bob_poit_x := types.ECDH(privRecipientKey, precursorPubKey) dh_Bob_poit_x := types.ECDH(privRecipientKey, precursorPubKey)
dBobHash, err := blake2b.New256(precursorPubKey.X.Bytes()) dBobHash, err := blake2b.New256(precursorPubKey.X.Bytes())
if err != nil { if err != nil {
...@@ -229,7 +228,7 @@ func AssembleReencryptFragment(privRecipient []byte, reKeyFrags []*ReKeyFrag) ([ ...@@ -229,7 +228,7 @@ func AssembleReencryptFragment(privRecipient []byte, reKeyFrags []*ReKeyFrag) ([
dhBob := dBobHash.Sum(nil) dhBob := dBobHash.Sum(nil)
dhBobBN := hashToModInt(dhBob) dhBobBN := hashToModInt(dhBob)
var share_key *EccPoit var result *EccPoit
if len(reKeyFrags) == 1 { if len(reKeyFrags) == 1 {
rPoint, err := NewEccPoint(reKeyFrags[0].ReKeyR) rPoint, err := NewEccPoint(reKeyFrags[0].ReKeyR)
if err != nil { if err != nil {
...@@ -242,7 +241,7 @@ func AssembleReencryptFragment(privRecipient []byte, reKeyFrags []*ReKeyFrag) ([ ...@@ -242,7 +241,7 @@ func AssembleReencryptFragment(privRecipient []byte, reKeyFrags []*ReKeyFrag) ([
return nil, err return nil, err
} }
share_key = rPoint.Add(uPoint).MulInt(dhBobBN) result = rPoint.Add(uPoint).MulInt(dhBobBN)
} else { } else {
var eFinal, vFinal *EccPoit var eFinal, vFinal *EccPoit
...@@ -284,8 +283,9 @@ func AssembleReencryptFragment(privRecipient []byte, reKeyFrags []*ReKeyFrag) ([ ...@@ -284,8 +283,9 @@ func AssembleReencryptFragment(privRecipient []byte, reKeyFrags []*ReKeyFrag) ([
eFinal = e.Add(eFinal) eFinal = e.Add(eFinal)
vFinal = v.Add(vFinal) vFinal = v.Add(vFinal)
} }
share_key = eFinal.Add(vFinal).MulInt(dhBobBN) result = eFinal.Add(vFinal).MulInt(dhBobBN)
} }
return share_key.ToPublicKey().SerializeCompressed(), nil share_key := crypto.KDF(result.ToPublicKey().SerializeCompressed(), 32)
return share_key, nil
} }
\ No newline at end of file
package sdk package sdk
import ( import (
"encoding/hex"
"errors" "errors"
"gitlab.33.cn/pengjun/reencrypt/sdk/crypto" "gitlab.33.cn/pengjun/reencrypt/sdk/crypto"
"gitlab.33.cn/pengjun/reencrypt/sdk/types" . "gitlab.33.cn/pengjun/reencrypt/sdk/types"
) )
func SignRawTransaction(raw string, privateKey string, signType string) (string, error) { func Sign(tx *Transaction, privateKey []byte, signType string) (*Transaction, error) {
var tx types.Transaction if signType == "" {
txByteData, err := types.FromHex(raw) signType = crypto.SECP256K1
if err != nil {
return "", err
} }
err = types.Decode(txByteData, &tx)
if err != nil {
return "", err
}
tx.Signature = nil tx.Signature = nil
if signType == crypto.SECP256K1 {
pub := crypto.PubKeyFromPrivate(privateKey)
if signType == "" { data := Encode(tx)
signType = crypto.SECP256k1 signature := crypto.Sign(data, privateKey)
} tx.Signature = &Signature{
signer := crypto.NewSignDriver(signType) Ty: 1,
if signer == nil { Pubkey: pub,
return "", errors.New("signType error") Signature: signature,
}
} else if signType == crypto.SM2 {
// TODO
} else if signType == crypto.ED25519 {
// TODO
} else {
return nil, errors.New("sign type not support")
} }
key, err := types.FromHex(privateKey) return tx, nil
if err != nil { }
return "", err
}
pub := signer.PubKeyFromPrivate(key)
data := types.Encode(&tx)
signature := signer.Sign(data, key)
tx.Signature = &types.Signature{
Ty: 1,
Pubkey: pub,
Signature: signature,
}
data = types.Encode(&tx) func cloneTx(tx *Transaction) *Transaction {
return hex.EncodeToString(data), nil copytx := &Transaction{}
copytx.Execer = tx.Execer
copytx.Payload = tx.Payload
copytx.Signature = tx.Signature
copytx.Fee = tx.Fee
copytx.Expire = tx.Expire
copytx.Nonce = tx.Nonce
copytx.To = tx.To
copytx.GroupCount = tx.GroupCount
copytx.Header = tx.Header
copytx.Next = tx.Next
return copytx
} }
func Hash(tx *Transaction) []byte {
copytx := cloneTx(tx)
copytx.Signature = nil
copytx.Header = nil
data := Encode(copytx)
return crypto.Sha256(data)
}
\ No newline at end of file
...@@ -194,7 +194,9 @@ func init() { ...@@ -194,7 +194,9 @@ func init() {
proto.RegisterType((*Signature)(nil), "types.Signature") proto.RegisterType((*Signature)(nil), "types.Signature")
} }
func init() { proto.RegisterFile("sdk.proto", fileDescriptor_70decb0fb6f436df) } func init() {
proto.RegisterFile("sdk.proto", fileDescriptor_70decb0fb6f436df)
}
var fileDescriptor_70decb0fb6f436df = []byte{ var fileDescriptor_70decb0fb6f436df = []byte{
// 255 bytes of a gzipped FileDescriptorProto // 255 bytes of a gzipped FileDescriptorProto
......
...@@ -6,6 +6,13 @@ import ( ...@@ -6,6 +6,13 @@ import (
"github.com/golang/protobuf/proto" "github.com/golang/protobuf/proto"
) )
//exec type
const (
ExecErr = 0
ExecPack = 1
ExecOk = 2
)
//FromHex hex -> []byte //FromHex hex -> []byte
func FromHex(s string) ([]byte, error) { func FromHex(s string) ([]byte, error) {
if len(s) > 1 { if len(s) > 1 {
...@@ -30,6 +37,16 @@ func ToHex(b []byte) string { ...@@ -30,6 +37,16 @@ func ToHex(b []byte) string {
return hex return hex
} }
//ToHex []byte -> hex
func ToHexPrefix(b []byte) string {
hex := hex.EncodeToString(b)
// Prefer output of "0x0" instead of "0x"
if len(hex) == 0 {
return ""
}
return "0x" + hex
}
//Encode 编码 //Encode 编码
func Encode(data proto.Message) []byte { func Encode(data proto.Message) []byte {
b, err := proto.Marshal(data) b, err := proto.Marshal(data)
...@@ -49,4 +66,4 @@ func ECDH(priv *secp256k1.PrivateKey, pub *secp256k1.PublicKey) []byte { ...@@ -49,4 +66,4 @@ func ECDH(priv *secp256k1.PrivateKey, pub *secp256k1.PublicKey) []byte {
ecKey := &secp256k1.PublicKey{} ecKey := &secp256k1.PublicKey{}
ecKey.X, ecKey.Y = secp256k1.S256().ScalarMult(pub.X, pub.Y, priv.D.Bytes()) ecKey.X, ecKey.Y = secp256k1.S256().ScalarMult(pub.X, pub.Y, priv.D.Bytes())
return ecKey.SerializeCompressed() return ecKey.SerializeCompressed()
} }
\ No newline at end of file
...@@ -5,10 +5,12 @@ ...@@ -5,10 +5,12 @@
package server package server
import ( import (
"encoding/hex"
"errors" "errors"
"fmt" "fmt"
"gitlab.33.cn/pengjun/reencrypt/sdk" "gitlab.33.cn/pengjun/reencrypt/sdk"
"gitlab.33.cn/pengjun/reencrypt/sdk/client" "gitlab.33.cn/pengjun/reencrypt/sdk/client"
"gitlab.33.cn/pengjun/reencrypt/sdk/types"
"time" "time"
) )
...@@ -43,13 +45,30 @@ func (pre *PreClient) RegisterPreNode(url, statkeAddr string) (string, error) { ...@@ -43,13 +45,30 @@ func (pre *PreClient) RegisterPreNode(url, statkeAddr string) (string, error) {
} }
// 签名 // 签名
signedTx, err := sdk.SignRawTransaction(res, pre.key, "") var tx types.Transaction
txByteData, err := types.FromHex(res)
if err != nil {
return "", err
}
err = types.Decode(txByteData, &tx)
if err != nil {
return "", err
}
keyByte, err := types.FromHex(pre.key)
if err != nil {
return "", err
}
signedTx, err := sdk.Sign(&tx, keyByte, "")
if err != nil { if err != nil {
return "", err return "", err
} }
// 发送 // 发送
hash, err := pre.client.SendTransaction(signedTx) data := types.Encode(signedTx)
hash, err := pre.client.SendTransaction(hex.EncodeToString(data))
if err != nil { if err != nil {
return "", err return "", err
} }
......
...@@ -57,7 +57,7 @@ func checkDhProof(key string, pub string, dh string) bool { ...@@ -57,7 +57,7 @@ func checkDhProof(key string, pub string, dh string) bool {
return false return false
} }
private := crypto.PrivateECDSAFromByte(keybyte[:]) private := crypto.PrivateFromByte(keybyte[:])
proof := types.ECDH(private, pubkey) proof := types.ECDH(private, pubkey)
if types.ToHex(proof) != dh { if types.ToHex(proof) != dh {
return false return false
...@@ -66,7 +66,7 @@ func checkDhProof(key string, pub string, dh string) bool { ...@@ -66,7 +66,7 @@ func checkDhProof(key string, pub string, dh string) bool {
} }
func generateDBKey(pubOwner string, pubRecipient string) []byte { func generateDBKey(pubOwner string, pubRecipient string) []byte {
return crypto.Sha256([]byte("PRE-"+pubOwner+"-"+pubRecipient)) return []byte("PRE-"+pubOwner+"-"+pubRecipient)
} }
func (service *NodeService) CollectFragment(fragments *common.ReqSendKeyFragment, result *interface{}) error { func (service *NodeService) CollectFragment(fragments *common.ReqSendKeyFragment, result *interface{}) error {
......
...@@ -208,7 +208,7 @@ func CheckExpireRoutine(db *leveldb.DB) { ...@@ -208,7 +208,7 @@ func CheckExpireRoutine(db *leveldb.DB) {
} }
if keyFragment.Expire != 0 && keyFragment.Expire <= now { if keyFragment.Expire != 0 && keyFragment.Expire <= now {
rlog.Info("Key Fragment Expired", "key", string(iter.Key())) rlog.Info("Key Fragment Expired", "key", string(iter.Key()), "expire", keyFragment.Expire)
remove = append(remove, iter.Key()) remove = append(remove, iter.Key())
} }
} }
......
...@@ -19,8 +19,8 @@ func handleReencrypt(t *testing.T, numSplit, threshold int, suffix string) { ...@@ -19,8 +19,8 @@ func handleReencrypt(t *testing.T, numSplit, threshold int, suffix string) {
bob, err := sdk.NewAccount("") bob, err := sdk.NewAccount("")
assert.Nil(t, err) assert.Nil(t, err)
enkey, pub_r, pub_u := sdk.GenerateEncryptKey(alice.PublicKey) enkey, pub_r, pub_u := sdk.GeneratePreEncryptKey(alice.PublicKey)
cipher, err := crypto.AESCBCPKCS7Encrypt(enkey[1:], []byte(msg)) cipher, err := crypto.AESCBCPKCS7Encrypt(enkey, []byte(msg))
assert.Nil(t, err) assert.Nil(t, err)
keyFragments, err := sdk.GenerateKeyFragments(alice.PrivateKey, bob.PublicKey, numSplit, threshold) keyFragments, err := sdk.GenerateKeyFragments(alice.PrivateKey, bob.PublicKey, numSplit, threshold)
...@@ -39,7 +39,7 @@ func handleReencrypt(t *testing.T, numSplit, threshold int, suffix string) { ...@@ -39,7 +39,7 @@ func handleReencrypt(t *testing.T, numSplit, threshold int, suffix string) {
services[i], err = NewNodeService(db, types.ToHex(serviceAcc.PrivateKey)) services[i], err = NewNodeService(db, types.ToHex(serviceAcc.PrivateKey))
assert.Nil(t, err) assert.Nil(t, err)
dhproof := types.ECDH(crypto.PrivateECDSAFromByte(alice.PrivateKey), crypto.PublicECDSAFromByte(serviceAcc.PublicKey)) dhproof := types.ECDH(crypto.PrivateFromByte(alice.PrivateKey), crypto.PublicFromByte(serviceAcc.PublicKey))
param := &common.ReqSendKeyFragment{ param := &common.ReqSendKeyFragment{
PubOwner: types.ToHex(alice.PublicKey), PubOwner: types.ToHex(alice.PublicKey),
PubRecipient: types.ToHex(bob.PublicKey), PubRecipient: types.ToHex(bob.PublicKey),
...@@ -79,7 +79,7 @@ func handleReencrypt(t *testing.T, numSplit, threshold int, suffix string) { ...@@ -79,7 +79,7 @@ func handleReencrypt(t *testing.T, numSplit, threshold int, suffix string) {
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, aesKey, enkey) assert.Equal(t, aesKey, enkey)
msgDecrypt, err := crypto.AESCBCPKCS7Decrypt(aesKey[1:], cipher) msgDecrypt, err := crypto.AESCBCPKCS7Decrypt(aesKey, cipher)
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, msg, string(msgDecrypt)) assert.Equal(t, msg, string(msgDecrypt))
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment