Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Task56 基于fisco账户体系,使用公钥加密AES密钥并分发。再使用AES加密数据进行上链 #155

Open
wants to merge 2 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions Doc-SIG/encrypt-onchaindata/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#### 支持环境
os: linux
arch: 仅测试amd64

#### 使用

*encrypt* 为编译好的linux/amd64 下的二进制文件,可以直接运行。

参数:

- -f [xx.pem] 指定.pem文件,加密模式时为公钥,解密时为私钥
- -c *e* 时为加密模式 *d* 为解密模式
- -t 加密模式时,为明文字符串(需要加密的内容);解密模式时为密文的base64字符串

在AES密钥分发的场景下,需要加密的内容则是**AES密钥**。

流程如下,alice为share合约的发起者,需要在这个合约上共享一些数据给bob和carlo,而不给dell。
1. alice收集bob和carlo的公钥
2. 使用bob和carlo各自的公钥给aes密钥加密,再发回给bob和carlo。
3. alice,bob,carlo,dell都可以使用share合约,但是alice,bob,carlo提交到share的数据都是经过aes密钥加密的,只有他们自己可以解密,dell看到的是密文。
33 changes: 33 additions & 0 deletions Doc-SIG/encrypt-onchaindata/cmd/wallet/wallet.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package main

import (
"crypto/ecdsa"
"fmt"
"log"

"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/crypto"
"golang.org/x/crypto/sha3"
)

func main() {
privateKey, err := crypto.GenerateKey()
if err != nil {
log.Fatal(err)
}
privateKeyBytes := crypto.FromECDSA(privateKey)
fmt.Println(hexutil.Encode(privateKeyBytes)[2:]) // 0xfad9c8855b740a0b7ed4c221dbad0f33a83a49cad6b3fe8d5817ac83d38b6a19
publicKey := privateKey.Public()
publicKeyECDSA, ok := publicKey.(*ecdsa.PublicKey)
if !ok {
log.Fatal("cannot assert type: publicKey is not of type *ecdsa.PublicKey")
}
publicKeyBytes := crypto.FromECDSAPub(publicKeyECDSA)
fmt.Println(hexutil.Encode(publicKeyBytes)[4:]) // 0x049a7df67f79246283fdc93af76d4f8cdd62c4886e8cd870944e817dd0b97934fdd7719d0810951e03418205868a5c1b40b192451367f28e0088dd75e15de40c05
address := crypto.PubkeyToAddress(*publicKeyECDSA).Hex()
fmt.Println(address) // 0x96216849c49358B10257cb55b28eA603c874b05E
hash := sha3.NewLegacyKeccak256()
hash.Write(publicKeyBytes[1:])
fmt.Println(hexutil.Encode(hash.Sum(nil)[12:])) // 0x96216849c49358b10257cb55b28ea603c874b05e
crypto.Keccak256(publicKeyBytes)
}
Binary file added Doc-SIG/encrypt-onchaindata/encrypt
Binary file not shown.
11 changes: 11 additions & 0 deletions Doc-SIG/encrypt-onchaindata/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
module encrypt-onchaindata

go 1.14

require (
github.com/JcobCN/goEncrypt v1.0.1
github.com/ethereum/go-ethereum v1.10.25
github.com/sirupsen/logrus v1.9.2 // indirect
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519
golang.org/x/sys v0.8.0 // indirect
)
591 changes: 591 additions & 0 deletions Doc-SIG/encrypt-onchaindata/go.sum

Large diffs are not rendered by default.

5 changes: 5 additions & 0 deletions Doc-SIG/encrypt-onchaindata/key.pem
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
-----BEGIN PRIVATE KEY-----
MIGEAgEAMBAGByqGSM49AgEGBSuBBAAKBG0wawIBAQQgXRrZ3U7FZ5CAygpW32Ya
L8Ts7+m1VDDRc5vV34m0F/qhRANCAAQerfbXSa/tjVnG2ZH5frU6su2EyS41oh1d
rRctMPV6PWqbw3IMrkC2gHenngbWnahzCcIB1YlWnWLV8KdbMqLp
-----END PRIVATE KEY-----
231 changes: 231 additions & 0 deletions Doc-SIG/encrypt-onchaindata/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,231 @@
package main

import (
"crypto/ecdsa"
"crypto/x509"
"encoding/base64"
"encoding/hex"
"encoding/pem"
"flag"
"fmt"
"io/ioutil"

"github.com/JcobCN/goEncrypt/ecc"
)

var (
pemFile string
crypt string
text string
)

func init() {
flag.StringVar(&pemFile, "f", "", "specific the PEM file")
flag.StringVar(&crypt, "c", "", "crypt option, e:encrypt or d:decrypt")
flag.StringVar(&text, "t", "", "in encrypt mode is plaintext, in decrypt mode is cipher text")
}

func readPem(pemPath string) ([]byte, error) {

b, err := ioutil.ReadFile(pemPath)
if err != nil {
return nil, fmt.Errorf("readPem error: %v", err)
}

p, _ := pem.Decode(b)
if p == nil {
return nil, fmt.Errorf("pem Decode error 'p' is nil")
}

return p.Bytes, nil
}

func getEccKey(privateKey *ecdsa.PrivateKey) (ecc.EccKey, error) {
privateBytes, err := x509.MarshalECPrivateKey(privateKey)
if err != nil {
return ecc.EccKey{}, err
}
publicBytes, err := x509.MarshalPKIXPublicKey(&privateKey.PublicKey)
if err != nil {
return ecc.EccKey{}, err
}
return ecc.EccKey{
PrivateKey: base64.StdEncoding.EncodeToString(privateBytes),
PublicKey: base64.StdEncoding.EncodeToString(publicBytes),
}, nil
}

func getEcdsaPrivateKeyBase64(privateKey *ecdsa.PrivateKey) (ecdsaPrivateKeyBase64 string, err error) {
privateBytes, err := x509.MarshalECPrivateKey(privateKey)
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(privateBytes), nil
}

func getEcdsaPublicKeyBase64(publicKey *ecdsa.PublicKey) (ecdsaPublicKeyBase64 string, err error) {
publicBytes, err := x509.MarshalPKIXPublicKey(publicKey)
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(publicBytes), nil
}

func s256Encrypt() error {

fmt.Println("Start to Encrypt by secp256k1....")

pubB, err := readPem(pemFile)
if err != nil {
return fmt.Errorf("read Pem error: %v", err)
}

// fmt.Println("publicKey is:" + hex.EncodeToString(pubB))
tempPubKey, err := x509.ParsePKIXPublicKey(pubB)
if err != nil {
return fmt.Errorf("x509 prase pubkey error: %v", err)
}
ecdsaPub, ok := tempPubKey.(*ecdsa.PublicKey)
if !ok {
return fmt.Errorf("can't assert to *ecdsa.PublicKey")
}
ecdsaPubB64, err := getEcdsaPublicKeyBase64(ecdsaPub)
if err != nil {
return fmt.Errorf("getEcdsaPubKeyBase64 : %v", err)
}

cipherText, err := ecc.EccEncryptToBase64([]byte(text), ecdsaPubB64)
if err != nil {
return fmt.Errorf("encrypt error: %v", err)
}
fmt.Println("cipherText:" + cipherText)

return nil
}

func s256Decrypt() error {

fmt.Println("Start to Decrypt by secp256k1....")

priB, err := readPem(pemFile)
if err != nil {
return fmt.Errorf("read Pem error: %v", err)
}

// fmt.Println("privateKey is:" + hex.EncodeToString(priB))
tempPriKey, err := x509.ParsePKCS8PrivateKey(priB)
if err != nil {
return fmt.Errorf("x509 prase prikey error: %v", err)
}
ecdsaPri, ok := tempPriKey.(*ecdsa.PrivateKey)
if !ok {
return fmt.Errorf("can't assert to *ecdsa.PrivateKey")
}
ecdsaPriB64, err := getEcdsaPrivateKeyBase64(ecdsaPri)
if err != nil {
return fmt.Errorf("getEcdsaPriKeyBase64 : %v", err)
}

plainBytes, err := ecc.EccDecryptByBase64(text, ecdsaPriB64)
if err != nil {
return fmt.Errorf("decrypt error: %v", err)
}
fmt.Println("plainText:" + string(plainBytes))

return nil
}

func test() {

priKey, err := readPem("key.pem")
if err != nil {
fmt.Printf("read ")
}

hexs := hex.EncodeToString(priKey)
fmt.Println("pem=" + hexs)

tempPrivateKey, err := x509.ParsePKCS8PrivateKey(priKey)
if err != nil {
fmt.Printf("x509,%v\n", err)
return
}
ecdsaPri, ok := tempPrivateKey.(*ecdsa.PrivateKey)
if ok == false {
fmt.Println("断言失败")
return
}

eccPri := ecc.ImportECDSA(ecdsaPri)
// eccPri.PublicKey.
// eccPri.D.Bytes()
fmt.Println(hex.EncodeToString(eccPri.D.Bytes()))
fmt.Println(hex.EncodeToString(eccPri.PublicKey.Curve.Params().B.Bytes()))
fmt.Println(hex.EncodeToString(eccPri.PublicKey.X.Bytes()))
fmt.Println(hex.EncodeToString(eccPri.PublicKey.Y.Bytes()))

pubB, err := readPem("pub.pem")
if err != nil {
fmt.Printf("read Pem error: %v\n", err)
}

fmt.Println(hex.EncodeToString(pubB))
tempPubKey, err := x509.ParsePKIXPublicKey(pubB)
if err != nil {
fmt.Errorf("x509 pubKey %v\n", err)
}
ecdsaPub, ok := tempPubKey.(*ecdsa.PublicKey)
if ok == false {
fmt.Errorf("断言失败=\n")
return
}
eccPub := ecc.ImportECDSAPublic(ecdsaPub)
fmt.Println(hex.EncodeToString(eccPub.X.Bytes()))
fmt.Println(hex.EncodeToString(eccPub.Y.Bytes()))

eccKey, err := getEccKey(ecdsaPri)
if err != nil {
fmt.Printf("getEccKey error=%v\n", err)
return
}
msg := "hello world"
cipherText, err := ecc.EccEncryptToBase64([]byte(msg), eccKey.PublicKey)
if err != nil {
fmt.Printf("encrypt,%v\n", err)
return
}
fmt.Println("密文:" + cipherText)

resMsg, err := ecc.EccDecryptByBase64(cipherText, eccKey.PrivateKey)
if err != nil {
fmt.Printf("EccDecryptError=%v\n", err)
return
}
fmt.Println(string(resMsg))
}

func main() {
flag.Parse()
// test()

if len(text) == 0 {
fmt.Println("Please enter 'text' flag -t , it must be need.")
return
}

if crypt == "e" {
err := s256Encrypt()
if err != nil {
fmt.Println(err)
}
} else if crypt == "d" {
err := s256Decrypt()
if err != nil {
fmt.Println(err)
}

} else {
fmt.Println("Please enter 'crypt' flag -c ")
return
}
}
4 changes: 4 additions & 0 deletions Doc-SIG/encrypt-onchaindata/pub.pem
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
-----BEGIN PUBLIC KEY-----
MFYwEAYHKoZIzj0CAQYFK4EEAAoDQgAEHq3210mv7Y1ZxtmR+X61OrLthMkuNaId
Xa0XLTD1ej1qm8NyDK5AtoB3p54G1p2ocwnCAdWJVp1i1fCnWzKi6Q==
-----END PUBLIC KEY-----