crypto

package module
v0.0.0-...-96d1451 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 26, 2023 License: Apache-2.0 Imports: 10 Imported by: 0

README

gitCrypto

Crypto Service Provider interface in go.

Table of Contents

Mockgen

Install mockgen : go get github.com/golang/mock/mockgen

How to use?

  • source: 指定接口文件
  • destination: 生成的文件名
  • package:生成文件的包名
  • imports: 依赖的需要import的包
  • aux_files:接口文件不止一个文件时附加文件
  • build_flags: 传递给build工具的参数

Eg.mockgen -destination mock/mock_crypto.go -package crypto -source crypto.go

Eg.mockgen -destination mock/mock_engine.go -package crypto -source engine.go

GitCZ

Note: Please use command npm install if you are the first time to use git cz in this repo.

Contribute

PRs are welcome!

Small note: If editing the Readme, please conform to the standard-readme specification.

License

This project is currently under Apache 2.0 license. See the LICENSE file for details

Documentation

Index

Constants

View Source
const (
	//Hash message digest algorithm
	Hash = 0
	//Asymmetric asymmetric encryption algorithm
	Asymmetric = 8
	//Symmetrical symmetric encryption algorithm
	Symmetrical = 16
)
View Source
const (
	//None unknown algorithm type, type information is hidden in the content, for example PKCS8
	None = 0x0

	//Hash
	FakeHash         = 0x00 << Hash
	SHA1             = 0x10 << Hash
	SHA2             = 0x20 << Hash
	SHA3             = 0x30 << Hash
	KECCAK           = 0x40 << Hash
	SM3              = 0x50 << Hash
	Sm3WithPublicKey = 0x60 << Hash //with default SM2 userID: 1234567812345678
	SelfDefinedHash  = 0x70 << Hash
	Size224          = 0x01 << Hash
	Size256          = 0x00 << Hash
	Size384          = 0x02 << Hash
	Size512          = 0x03 << Hash
	SHA2_224         = SHA2 | Size224
	SHA2_256         = SHA2 | Size256
	SHA2_384         = SHA2 | Size384
	SHA2_512         = SHA2 | Size512
	SHA3_224         = SHA3 | Size224
	SHA3_256         = SHA3 | Size256
	SHA3_384         = SHA3 | Size384
	SHA3_512         = SHA3 | Size512
	KECCAK_224       = KECCAK | Size224
	KECCAK_256       = KECCAK | Size256
	KECCAK_384       = KECCAK | Size384
	KECCAK_512       = KECCAK | Size512

	//Asymmetric Algo
	Sm2p256v1        = 0x01 << Asymmetric
	Secp256k1        = 0x02 << Asymmetric
	Secp256r1        = 0x03 << Asymmetric
	Secp384r1        = 0x04 << Asymmetric
	Secp521r1        = 0x05 << Asymmetric
	Secp256k1Recover = 0x06 << Asymmetric
	SelfDefinedSign  = 0x07 << Asymmetric
	Rsa2048          = 0x10 << Asymmetric
	Rsa3072          = 0x11 << Asymmetric
	Rsa4096          = 0x12 << Asymmetric
	Ed25519          = 0x20 << Asymmetric

	//Symmetrical Algo for Encrypt and Decrypt
	Sm4              = 0x01 << Symmetrical
	Aes              = 0x02 << Symmetrical
	Des3             = 0x03 << Symmetrical
	TEE              = 0x04 << Symmetrical
	SelfDefinedCrypt = 0x05 << Symmetrical
	WhiteBox         = 0x06 << Symmetrical
	CBC              = 0x10 << Symmetrical
	ECB              = 0x20 << Symmetrical
	GCM              = 0x30 << Symmetrical
)

algorithm identifier const value table

View Source
const (
	DEBUG = iota
	Info
	Notice
	Warning
	Error
)

context status

View Source
const (
	CurveNameBN254          = "bn254"
	CurveNameSM9            = "sm9"
	CurveNameCurve101       = "testCurve101"
	CurveNameCurve101NonFFT = "testCurve101NonFFT"
)

curve name

View Source
const (
	ST_ONE = 1 + iota
	ST_OUTPUT
	ST_PUBINPUT
	ST_PRVINPUT
	ST_INTERNAL  //除1、输入和输出外的骨干信号
	ST_DISCARDED //边缘信号,总是依附于某个骨干信号; 无用的信号
	ST_CONSTANT  //常量信号,即被赋值为N的信号
)

nolint

View Source
const (
	Groth16        = 0x00
	AlgoTypeOffset = 32
)

zkp algo

View Source
const (
	AlgoGroth16 = "groth16"
	AlgoPlonk   = "plonk"
)

algo name

View Source
const MethodName = "NewSDK"

MethodName plugin function name

View Source
const (
	ProofVersion1 = 0x01 << iota
)

ProofVersion1 version for proof unmarshal

View Source
const (
	VerifyVersion1 = 0x01 << iota
)

VerifyVersion1 version for evm unmarshal

Variables

View Source
var ErrFFT = errors.New("not support fft")

ErrFFT not support fft

View Source
var ErrNotSupport = fmt.Errorf("engine: this algo is not support")

ErrNotSupport this algo is not support

Functions

func ErrDevice

func ErrDevice(msg string) error

ErrDevice device internal error

func ErrIndexMissing

func ErrIndexMissing(index []byte) error

ErrIndexMissing index missing

func GetBigInt

func GetBigInt() *big.Int

GetBigInt get *big.Int

func PutBigInt

func PutBigInt(in *big.Int)

PutBigInt put *big.Int

func RegisterPairing

func RegisterPairing(p Pairing)

RegisterPairing register pairing

Types

type AlgebraicSys

type AlgebraicSys interface {
	Marshaller
	GetModule() *big.Int
	Name() string
	NewScalar() FieldElement //fr
	//NewField() FieldElement  //fp
	PutScalar(FieldElement)
	GetRootOfUnity(uint64) (FieldElement, uint64, error)
}

AlgebraicSys algebra system

type CA

type CA interface {
	GetHostName() string
	GetKeyIdentifier() []byte
	//GetPubKeyForPairing 返回key,用于和ca的私钥配对(典型值为65字节),仅在分布式CA中调用
	GetPubKeyForPairing() []byte
	String() string
}

type Cert

type Cert interface {
	GetCertType() CertType
	GetHostName() string
	GetCAHostName() string
	GetExtName() map[string]string
	GetAuthorityKeyIdentifier() []byte
	String() string
	GetVerifyKey() VerifyKey
	VerifyCert(caList []string) error
}

type CertType

type CertType int

CertType a data type to present cert type,like tcert,ecert and so on to install stringer: go install golang.org/x/tools/cmd/...@v0.1.12

const (
	ECert           CertType = iota //ecert
	RCert                           //rcert
	SDKCert                         //sdkcert
	TCert                           //tcert
	ERCert                          //ercert
	IDCert                          //idcert
	RAWPub                          //rawpub
	UnknownCertType                 //unknown_cert_type
)

the value of CertType

func (CertType) String

func (i CertType) String() string

type ChainSDK

type ChainSDK interface {
	//ChainType 返回链的类型
	ChainType() string
	//InvokeFinish 调用Finish方法, namespace是分区(通道),address是合约地址(名称)
	InvokeFinish(nodes []string, address, taskID, proof, result, error string) ([]byte, error)
	//RegisterListening 注册监听EVENT_FINISH和EVENT_COMPUTE事件
	RegisterListening(proxyAddress, businessAddress []string) (chan *Event, error)
	//UnregisterListening 解注册事件
	UnregisterListening(address string) error
}

ChainSDK sdk for specific blockchain

type ChainType

type ChainType string

ChainType chain type

const (
	VMEvm       ChainType = "EVM"
	VMChainCode ChainType = "ChainCode"
)

chain type enum

type Cryptor

type Cryptor interface {
	Encryptor
	Decryptor
}

Cryptor is interface that provide crypto function deprecated

type DecKey

type DecKey interface {
	EncKey
	Decrypt(cipher []byte) ([]byte, error)
	Destroy()
}

DecKey private key which can decrypt

type Decryptor

type Decryptor interface {
	// Decrypt decrypts ciphertext using key k.
	Decrypt(k, cipherText []byte) (plaintext []byte, err error)
}

Decryptor is a interface that provides decryption algorithms

type EncKey

type EncKey interface {
	GetKeyInfo() int
	Encrypt(msg []byte, reader io.Reader) ([]byte, error)
	//Bytes for more information, see  comment of VerifyKey.Bytes
	Bytes() []byte
}

EncKey public key which can encrypt

type Encryptor

type Encryptor interface {
	// Encrypt encrypts plaintext using key k.
	Encrypt(k, plaintext []byte, reader io.Reader) (cipherText []byte, err error)
}

Encryptor is a interface that provides encryption algorithms

type Event

type Event struct {
	ChannelID string    `json:"channelID"`
	Type      EventType `json:"type"`
	Event     []byte    `json:"event"` //json content
	TxHash    string    `json:"txHash"`
	BlockNum  int       `json:"blockNum"`
}

Event event

type EventCompute

type EventCompute struct {
	TaskID                 string   `json:"taskID"`
	CircuitID              [32]byte `json:"circuitID"`
	CCName                 string   `json:"ccName"`
	WebHook                string   `json:"webHook"`
	WebHookBodyPattern     string   `json:"webHookBodyPattern"`
	BusinessContractAddr   string   `json:"businessContractAddr"`
	BusinessContractMethod string   `json:"businessContractMethod"`
	Input                  string   `json:"input"`
}

EventCompute event compute

type EventFinish

type EventFinish struct {
	TaskID      string   `json:"taskID"`
	CircuitID   [32]byte `json:"circuitID"`
	Proof       string   `json:"proof"`
	Result      string   `json:"result"`
	Error       string   `json:"error"`
	Response    []byte   `json:"response"`
	NextCompute []byte   `json:"nextCompute"`
}

EventFinish event finish

type EventType

type EventType int

EventType type EventType

const (
	EventTypeCompute EventType = iota
	EventTypeFinish
)

event type

type FieldElement

type FieldElement interface {
	UnmarshalJSON([]byte) error
	MarshalJSON() ([]byte, error)
	Add(a1, a2 FieldElement) FieldElement
	Double(FieldElement) FieldElement
	Sub(a1, a2 FieldElement) FieldElement
	Neg(FieldElement) FieldElement
	Mul(a1, a2 FieldElement) FieldElement
	Square(FieldElement) FieldElement
	Div(a1, a2 FieldElement) FieldElement
	Inv(FieldElement) FieldElement
	Exp(FieldElement, []byte) FieldElement

	Equal(FieldElement) bool
	IsZero() bool
	IsOne() bool
	IsNeg() bool

	Set(FieldElement) FieldElement
	SetOne() FieldElement
	SetZero() FieldElement
	SetInt64(int64) FieldElement
	SetUint64(uint64) FieldElement
	SetRandom(io.Reader) FieldElement

	// From sets self to v (regular form) and returns self (Montgomery form)
	From(rat *big.Int) FieldElement
	//Regular append regular bytes to 'in', keep 'z' unchanged
	Regular(in []byte) []byte
	//FromRegular interprets 'content' as the bytes of a big-endian unsigned integer,
	// sets z to that value (in Montgomery form), and returns z.
	FromRegular(content []byte) FieldElement

	//MontBytes set and return 'res' with bytes in Montgomery form
	MontBytes(res []byte) []byte

	//GetModule set 'b' to 21888242871839275222246405745257275088548364400416034343698204186575808495617
	GetModule(*big.Int)
	String() string
	//Copy get a clone
	Copy() FieldElement
}

FieldElement in Montgomery From

type FlagReader

type FlagReader interface {
	io.Reader
	GetFlag() int
}

FlagReader reader use as flag

type Hasher

type Hasher interface {
	hash.Hash
	// Hash hashes messages msg.
	Hash(msg []byte) (hash []byte, err error)
	// BatchHash If you need to hash a series of bytes slices, calling BachHash can reduce one copy. BenchHash implies a loop.
	// example: a,b,c,d are four big byte slice
	// BenchHash([][]bytes{a,b,c,d}) faster than Hash(bytes.Join([][]bytes{a,b,c,d},nil))
	// It reduce one join(...). Join implies one copy.
	BatchHash(msg [][]byte) (hash []byte, err error)
}

Hasher is a interface that provides hash algorithms

type Key

type Key interface {
	// Bytes converts this key to its byte representation,
	// if this operation is allowed.
	Bytes() ([]byte, error)

	//FromBytes It's revert method to Bytes()
	//K is a byte that needs to be parsed, and the meaning of opt depend on Keys, for example, it's maybe an algorithm type. If the parsing fails, return empty Key or nil.
	FromBytes(k []byte, opt int) error
}

Key represents a cryptographic key

type Level

type Level interface {
	//GetLevel the second return value is reserved and has NO effect at present!
	GetLevel() ([]int, uint8)
}

Level priority of plugins

type Logger

type Logger interface {
	Debug(v ...interface{})
	Debugf(format string, v ...interface{})
	Info(v ...interface{})
	Infof(format string, v ...interface{})
	Notice(v ...interface{})
	Noticef(format string, v ...interface{})
	Warning(v ...interface{})
	Warningf(format string, v ...interface{})
	Error(v ...interface{})
	Errorf(format string, v ...interface{})
	Critical(v ...interface{})
	Criticalf(format string, v ...interface{})
}

Logger interface

type MPC

type MPC interface {
	New(curve string, power uint) []byte
	Contribute(entropy, name string) error
	Verify() (bool, error)
	Beacon(string, int) error
	GetPower() int
	GetG1() []Point
	GetG2() []Point
	GetPairing() string
	GetHash() string
	VerifyWithHistory(srsBefore MPC) (bool, error)
	Marshaller
}

MPC mpc

type Marshaller

type Marshaller interface {
	Marshal() []byte
	Unmarshal([]byte) ([]byte, error)
}

Marshaller marshal and unmarshal

type NewSDKFunc

type NewSDKFunc func(path, user, namespace string, logger Logger) (ChainSDK, error)

NewSDKFunc plugin function type

type Pairing

type Pairing interface {
	AlgebraicSys
	Pair([]Point, []Point) Point
	PairCheck(P []Point, Q []Point) bool
	IsOnCurve(Point) error
	//GetBase never change result's value for GetBase, GetModule and GetOlder!
	GetBase(Position) Point
	NewPoint(Position) Point
	BatchScalarMultiplicationG1(scalars []*big.Int, ret []Point)
	BatchScalarMultiplicationG2(scalars []*big.Int, ret []Point)
}

Pairing pairing of elliptic

func UnMarshalPairing

func UnMarshalPairing(data []byte) Pairing

UnMarshalPairing unmarshal pairing

type PluginCryptFunc

type PluginCryptFunc interface {
	Level
	GetSecretKey(mode int, pwd, key []byte) (SecretKey, error)
}

PluginCryptFunc symmetric encryption and decryption function

type PluginGenerateSessionKeyFunc

type PluginGenerateSessionKeyFunc interface {
	Level
	KeyAgreementInit(curve elliptic.Curve) (data1, data2ToPeer []byte, err error)
	KeyAgreementFinal(curve elliptic.Curve, algo string, data1, data2FromPeer []byte) (SecretKey, error)
}

type PluginHashFunc

type PluginHashFunc interface {
	Level
	GetHash(mode int) (Hasher, error)
}

PluginHashFunc hash function

type PluginRandomFunc

type PluginRandomFunc interface {
	Level
	Rander() (io.Reader, error)
}

PluginRandomFunc random function

type PluginSignFuncL0

type PluginSignFuncL0 interface {
	Level
	//GetVerifyKey enter a raw publicKey and mod, return a VerifyKey
	//a raw publicKey means:
	// 1) for sm2, key is 65bytes and in 0x04||X||Y form, see GMT0009-2012 7.1
	//      http://www.gmbz.org.cn/main/viewfile/2018011001400692565.html may help
	// 2) for ecdsa, key is in 0x04||X||Y. The length depends on the curve, for example,
	//		65 bytes for secp256k1 and 133 for secp521r1, see 2.3.3 in [SEC1] uncompressed form.
	//		https://www.rfc-editor.org/rfc/rfc5480.txt may help
	GetVerifyKey(key []byte, mode int) (VerifyKey, error)
}

PluginSignFuncL0 sign function

type PluginSignFuncL1

type PluginSignFuncL1 interface {
	PluginSignFuncL0
	//GetSignKey parse printable keyIndex to SignKey
	GetSignKey(keyIndex string) (SignKey, error)
}

type PluginSignFuncL2

type PluginSignFuncL2 interface {
	PluginSignFuncL1
	//CreateSignKey generate a sign key
	CreateSignKey() (index string, k SignKey, err error)
	//ParseCertificate for x509, input is PEM or self-defined TXT
	ParseCertificate(string) (Cert, error)
	//ParseAllCA parse ca
	ParseAllCA([]string) ([]CA, error)
}

type PluginSignFuncL3

type PluginSignFuncL3 interface {
	PluginSignFuncL2
	//Issue ext for NVP and LP: key is pkix.Platform, pkix.Version, pkix.VP
	Issue(ca CA, hostname string, ct CertType, ext map[string]string, vk VerifyKey) ([]byte, error)
	GenerateLocalCA(hostName string) (skIndex string, ca CA, err error)
}

type Point

type Point interface {
	Marshaller
	Add(Point, Point) Point
	Set(Point) Point
	Double(Point) Point
	//Neg neg
	Neg(Point) Point
	ScalarMult(Point, *big.Int) Point //scalar is at Z+
	ScalarBaseMult(*big.Int) Point
	//GetPosition get position
	GetPosition() Position
	GetPairing() Pairing
	SetInfinity()
	IsInfinity() bool
}

Point elliptic point

type Position

type Position int

Position position in Pairing

const (
	G1 Position = 1 << iota
	G2
	GT
)

Position in Pairing

type PrivateKey

type PrivateKey interface {
	SignKey
	DecKey
}

PrivateKey represents the private key, able to sign and decrypt

type ProveKey

type ProveKey interface {
	Prove(cs R1CS, witness []FieldElement, mpc MPC) ([]byte, error)
	GetSnark() string
	GetPairing() string
	GetVKTag() string
	Marshaller
}

ProveKey zk-SNARKs algorithm prove key

type ProverInfo

type ProverInfo map[string][]*big.Int

ProverInfo witness

type PublicKey

type PublicKey interface {
	VerifyKey
	EncKey
}

PublicKey represents the public key, capable of verification and encryption

type R1CS

type R1CS interface {
	fmt.Stringer
	R1CSIterator
	SignalNum() int //m
	InputNum() (privateInput, publicInput int)
	OutputNum() int // l = publicInput + OutputNum() + 1 = m - privateInput
	Marshal() []byte
	GetPairing() Pairing
}

R1CS r1cs

type R1CSIterator

type R1CSIterator interface {
	ConstraintsNum() uint64
	Next(pos *int) (index int, a, b, c map[int]FieldElement)
	GetSignalByID(nowid int) (id, reoffset int, prefix string, value FieldElement)
}

R1CSIterator r1cs iterator

type Response

type Response struct {
	Continue bool `json:"continue"`
	//NextParam: proxyContractAddr, input, businessContractAddr, businessContractMethod, WebHook and WebHookBodyPattern
	NextParam [6]string `json:"nextParam"`
	//response
	Response []byte `json:"response"`
}

Response callback response

type SecretKey

type SecretKey interface {
	Encrypt(src []byte, reader io.Reader) []byte
	Decrypt(src []byte) []byte
	Destroy()
}

SecretKey sym

type SignKey

type SignKey interface {
	VerifyKey
	Sign(msg []byte, hasher hash.Hash, rand io.Reader) ([]byte, error)
	Destroy()
}

SignKey private key which can sign

type Signer

type Signer interface {
	Key
	Sign(k, digest []byte, reader io.Reader) ([]byte, error)
}

Signer sign

type Snarks

type Snarks interface {
	Name() string
	Setup(r1cs R1CS) (ProveKey, VerifyProofKey, error)
	GenCode(p, v []byte, circuitID [32]byte, t ChainType) []byte
	UnmarshalVK(in []byte) (VerifyProofKey, error)
	UnmarshalPK(in []byte) (ProveKey, error)
}

Snarks zk-SNARKS

type VCMetrics

type VCMetrics interface {
	UpdateGetDataTime(s, e int64)
	UpdateWaitTime(s, e int64)
	UpdateProveTime(s, e int64)
	UpdateVerifyTime(s, e int64)
	UpdateComputerTime(s, e int64)
	UpdateG1TPS(s, e int64, n int)
	UpdateG2TPS(s, e int64, n int)
}

VCMetrics metrics for prove and verify

type Verifier

type Verifier interface {
	Key
	// Verify verifies signature against key k and digest
	Verify(k, signature, digest []byte) (valid bool, err error)
}

Verifier is a interface that provides verifying algorithms

type VerifyKey

type VerifyKey interface {
	GetKeyInfo() int
	Verify(msg []byte, hasher hash.Hash, sig []byte) bool
	//Bytes return a raw key bytes without algorithm information
	//sm2: SM2PublicKey::=BIT STRING,	04||X||Y,	65 Bytes,	GMT0009-2012 7.1
	//ecdsa: PublicKeyBytes in PKIX publicKey
	//rsa: asn1{N, e}
	//matching public and private key pairs need to return the same result
	Bytes() []byte
	//RichBytes return a bytes with algorithm information
	RichBytes() []byte
}

VerifyKey public key which can verify for more information, see GetVerifyKey's comment

type VerifyProofKey

type VerifyProofKey interface {
	Verify(in []byte, limit string, mpc MPC) error
	GetSnark() string
	GetPairing() string
	Marshaller
}

VerifyProofKey vk

Directories

Path Synopsis
Package crypto is a generated GoMock package.
Package crypto is a generated GoMock package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL