secio

package
v0.0.0-...-34879f3 Latest Latest
Warning

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

Go to latest
Published: Dec 15, 2022 License: MIT Imports: 29 Imported by: 0

README

tentacle-secio-go

This is the Go implementation of the secio layer in the tentacle framework. Currently, it can already shake hands and communicate normally. The protocol can be seen in the Rust version.

Usage

client:

func main() {
    key := secio.GenerateSecp256k1()
    config := secio.NewConfig(key)

    // Get a TCP connection
    conn, _ := net.Dial("tcp", ":1337")

    sec, _ := config.Handshake(conn)
    sec.Write([]byte("hello world"))
    recv := make([]byte, 11)
    sec.Read(recv)
}

server:

func main() {
    key := GenerateSecp256k1()
    config := NewConfig(key)

    listener, _ := net.Listen("tcp", ":0")
    defer listener.Close()

    for {
        conn, _ := listener.Accept()
        go func() {
            sec, _ := config.Handshake(conn)
            recv := make([]byte, 11)
            sec.Read(recv)
            sec.Write(recv)
        }()
    }
}

Thanks

Most of this project is a translation of the implementation of the Rust version, and a small part borrows from the go-libp2p-secio project

Documentation

Index

Constants

View Source
const AES128GCM = "AES-128-GCM"

AES128GCM is aead encryption algorithm

View Source
const AES256GCM = "AES-256-GCM"

AES256GCM is aead encryption algorithm

View Source
const CHACHA20POLY1305 = "CHACHA20_POLY1305"

CHACHA20POLY1305 is aead encryption algorithm

View Source
const DefaultAgreementsProposition = "P-256,P-384,X25519"

DefaultAgreementsProposition is the default ECDH algorithm

View Source
const DefaultCiphersProposition = "AES-128-GCM,AES-256-GCM,CHACHA20_POLY1305"

DefaultCiphersProposition is the default aead encryption algorithm

View Source
const DefaultDigestsProposition = "SHA256,SHA512"

DefaultDigestsProposition is the default hash algorithm used in handshake

View Source
const ECDHP256 = "P-256"

ECDHP256 is ECDH algorithm

View Source
const ECDHP384 = "P-384"

ECDHP384 is ECDH algorithm

View Source
const PrivKeyBytesLen = 32
View Source
const SHA256 = "SHA256"

SHA256 is hash algorithm

View Source
const SHA256CODE = 0x12

SHA256CODE code

View Source
const SHA256SIZE = 32

SHA256SIZE 32

View Source
const SHA512 = "SHA512"

SHA512 is hash algorithm

View Source
const X25519 = "X25519"

X25519 is ECDH algorithm

Variables

View Source
var (
	ErrUnknownCode   = errors.New("unknown multihash code")
	ErrTooShort      = errors.New("peer id too short. must be >= 2 bytes")
	ErrInvalidPeerID = errors.New("input isn't valid peer id")

	ErrVarintBufferShort = errors.New("uvarint: buffer too small")
	ErrVarintTooLong     = errors.New("uvarint: varint too big (max 64bit)")
)

errors

View Source
var ErrConnectSelf = errors.New("ConnectSelf")

ErrConnectSelf means node handshake with self

View Source
var ErrDecipherFail = errors.New("Can not decipher remote data")

ErrDecipherFail means failure to decode remote data

View Source
var ErrEphemeralKeyGenerationFailed = errors.New("Failed to generate ephemeral key")

ErrEphemeralKeyGenerationFailed means failed to generate ephemeral key

View Source
var ErrFrameTooShort = errors.New("short packet")

ErrFrameTooShort means frame is wrong

View Source
var ErrInvalidData = errors.New("Invalid data")

ErrInvalidData means unable to parse remote's data

View Source
var ErrNoCommonAlgorithms = errors.New("No algorithms in common")

ErrNoCommonAlgorithms means can't find same propose algorithms

View Source
var ErrSecretGenerationFailed = errors.New("Failed to generate the secret shared key from the ephemeral key")

ErrSecretGenerationFailed means failed to generate the secret shared key

View Source
var ErrVerificationFail = errors.New("Failed Verification signature")

ErrVerificationFail means handshake verification failure

Functions

func Bytes2str

func Bytes2str(b []byte) string

Bytes2str convert to string in place

func Str2bytes

func Str2bytes(s string) []byte

Str2bytes convert to bytes in place https://www.cnblogs.com/shuiyuejiangnan/p/9707066.html

Types

type Config

type Config struct {
	// contains filtered or unexported fields
}

Config of handshake

func NewConfig

func NewConfig(k PrivKey) *Config

NewConfig return a default config

func (*Config) Ciphers

func (c *Config) Ciphers(ci string) *Config

Ciphers try replace default ciphers function but if new one can't supported by this library, it will do nothing

func (*Config) Digests

func (c *Config) Digests(d string) *Config

Digests try replace default digests function but if new one can't supported by this library, it will do nothing

func (*Config) Handshake

func (c *Config) Handshake(conn net.Conn) (*SecureConn, error)

Handshake attempts to perform a handshake on the given socket.

func (*Config) KeyAgreements

func (c *Config) KeyAgreements(agreement string) *Config

KeyAgreements try replace default agreements function but if new one can't supported by this library, it will do nothing

func (*Config) MaxFrameLength

func (c *Config) MaxFrameLength(size int) *Config

MaxFrameLength replace default frame size, default is 8M

type GenSharedKey

type GenSharedKey func([]byte) ([]byte, error)

GenSharedKey generates the shared key from a given private key

func GenerateEphemeralKeyPair

func GenerateEphemeralKeyPair(curveName string) ([]byte, GenSharedKey, error)

GenerateEphemeralKeyPair returns an ephemeral public key and returns a function that will compute the shared secret key.

type Key

type Key interface {
	// Bytes returns raw bytes
	Bytes() []byte

	// Equals checks whether two PubKeys are the same
	Equals(Key) bool

	// TypeID return molecule union ID
	TypeID() mol.Number

	// PeerID generate a peer id from key
	PeerID() PeerID
}

Key represents a crypto key that can be compared to another key

type PeerID

type PeerID []byte

PeerID is a byte slice

func PeerIDFromBese58

func PeerIDFromBese58(s string) (p PeerID, e error)

PeerIDFromBese58 parses a Bese58-encoded string.

func PeerIDFromBytes

func PeerIDFromBytes(data []byte) (PeerID, error)

PeerIDFromBytes parses a slice

func PeerIDFromKey

func PeerIDFromKey(k Key) PeerID

PeerIDFromKey return a PeerID from the key

func RandomPeerID

func RandomPeerID() PeerID

RandomPeerID return a random PeerID

func (PeerID) Bese58String

func (p PeerID) Bese58String() string

Bese58String return bs58 format string

func (*PeerID) Bytes

func (p *PeerID) Bytes() []byte

Bytes return bytes

func (*PeerID) IsKey

func (p *PeerID) IsKey(k Key) bool

IsKey compare peer id with key

type PrivKey

type PrivKey interface {
	Key

	// Cryptographically sign the given bytes
	Sign([]byte) ([]byte, error)

	// Return a public key paired with this private key
	GenPublic() PubKey
}

PrivKey represents a private key that can be used to generate a public key and sign data

func GenerateSecp256k1

func GenerateSecp256k1() PrivKey

GenerateSecp256k1 return a random Secp256k1 private key

func Secp256k1FromBytes

func Secp256k1FromBytes(key []byte) (PrivKey, error)

Secp256k1FromBytes return private key from bytes

type PubKey

type PubKey interface {
	Key

	// Verify that 'sig' is the signed hash
	Verify(message []byte, sig []byte) error

	// Encode return molecule-encodes bytes
	Encode() []byte
}

PubKey is a public key that can be used to verifiy data signed with the corresponding private key

func DecodeToSecpPub

func DecodeToSecpPub(data []byte) (PubKey, error)

DecodeToSecpPub try parse bytes from molecule-encodes byte

type SecureConn

type SecureConn struct {
	// contains filtered or unexported fields
}

SecureConn is a stream for secio Note: Please do not use streaming read and msg read interchangeably, as this may cause data confusion

func (*SecureConn) Close

func (sec *SecureConn) Close() error

Close closes the connection.

func (*SecureConn) LocalAddr

func (sec *SecureConn) LocalAddr() net.Addr

LocalAddr returns the local network address.

func (*SecureConn) NextMsgLen

func (sec *SecureConn) NextMsgLen() (int, error)

NextMsgLen repub msgio.ReadWriteClose

func (*SecureConn) Read

func (sec *SecureConn) Read(b []byte) (n int, err error)

func (*SecureConn) ReadMsg

func (sec *SecureConn) ReadMsg() ([]byte, error)

ReadMsg repub msgio.ReadWriteCloser

func (*SecureConn) ReleaseMsg

func (sec *SecureConn) ReleaseMsg(b []byte)

ReleaseMsg repub msgio.ReadWriteCloser

func (*SecureConn) RemoteAddr

func (sec *SecureConn) RemoteAddr() net.Addr

RemoteAddr returns the remote network address.

func (*SecureConn) RemotePub

func (sec *SecureConn) RemotePub() PubKey

RemotePub return remote pubkey

func (*SecureConn) SetDeadline

func (sec *SecureConn) SetDeadline(t time.Time) error

SetDeadline call inner conn set deadline

func (*SecureConn) SetReadDeadline

func (sec *SecureConn) SetReadDeadline(t time.Time) error

SetReadDeadline call inner conn set read deadline

func (*SecureConn) SetWriteDeadline

func (sec *SecureConn) SetWriteDeadline(t time.Time) error

SetWriteDeadline call inner conn set write deadline

func (*SecureConn) Write

func (sec *SecureConn) Write(b []byte) (int, error)

func (*SecureConn) WriteMsg

func (sec *SecureConn) WriteMsg(b []byte) error

WriteMsg repub msgio.ReadWriteClose

type StreamCipher

type StreamCipher interface {
	Encrypt(input []byte) []byte
	Decrypt(input []byte) ([]byte, error)
}

StreamCipher a cipher of aead stream

func AESGCM

func AESGCM(psk []byte) (StreamCipher, error)

AESGCM creates a new Cipher with a pre-shared key. len(psk) must be one of 16 or 32 to select AES-128/256-GCM.

func Chacha20Poly1305

func Chacha20Poly1305(psk []byte) (StreamCipher, error)

Chacha20Poly1305 creates a new Cipher with a pre-shared key. len(psk) must be 32.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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