crypka

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Mar 16, 2022 License: MIT Imports: 23 Imported by: 0

README

crypka

Crypka is library, which abstracts away crypto, so one can easily do:

  • Swap cryptosystems by swapping algorithm object in one place
  • Easily and securely marshal keys

Crypka also implemented benchamrking and testing utils for various packag crypto primitives like signing or encryption.

Testing API for now is subject to changes.

Algorithms

For now following algorithms are implemented and integrated with crypka:

  • Symmetric signing using STL hashes
  • Symmetric signing using HMAC + STL hashes
  • Asymmetric signing using ed25519
  • Key exchange using x25519
  • Asymmetric encryption using symmetric encryption algo and key exchange algorithm
  • Symmetric encryption using any AEAD cipher from golang's STL
  • Symmetric stream encryption using any symmetric encryption(with authentication and truncation-prevention); think of SSL for files
  • RNG from any stream cipher
  • IEC78164 padding algorithm

Why even bother doing something like that?

There is a couple of reasons:

  • (IMO) nobody has created library, which allows easy cryptosystem swapping, so one could go from RSA4096 to some quantumm secure algorithm by swapping single algorithm declaration
  • Since it allows easy algorithm swapping, it simplifies performance testing with various algorithms
  • Also APIs here are designed in a way, which is easy for end user(not that much consise though). If some crypto API can be implemented in slower but less error prone way, crypka will provide the 2nd one.

TODOs:

  • Support for post quantumm algorithms
  • Rekeing for stream encryptors, so one can encrypt infiite amount of data
  • Slow hashes for passwords and and proof of work
  • Better struct hashing, preferrably automated via reflection with possibility to implement interface manually, just like encoding/json package with marshalJSON
  • Implement methods like marshalJson and other, so keys can be marshaled to JSON automatically without calling MarhsalToWriter

Documentation

Index

Constants

View Source
const (
	ByteVar intEncoding = 0 // default is variable
	Byte1   intEncoding = 1
	Byte2   intEncoding = 2
	Byte4   intEncoding = 4
	Byte8   intEncoding = 8
)
View Source
const ReasonableRNGSeedLength = 32

Variables

View Source
var ErrEncAlreadyFinalized = errors.New("crypka: encryption was already finalized")
View Source
var ErrEncAuthFiled = errors.New("crypka: Authentication of decrypted text filed. Message has been modified")
View Source
var ErrEncInvalidNonceType = errors.New("crypka: invalid NonceType value was provided")
View Source
var ErrEncStreamChunkTooBig = errors.New("crypka: streamming encryption chunk is too big and won't be decrypted")
View Source
var ErrEncStreamCorrupted = errors.New("crypka: stream chunks were corrupted or reordered or stream was truncated or finalization chunks was not found")
View Source
var ErrEncStreamUnsupportedCPK = errors.New("crpyka: found unknown CPK control value in decryption stream. data is either corrupted or decryptor version is too old")
View Source
var ErrEncTooManyChunksEncrypted = errors.New("crypka: Encryptor can't encrypt securely any more chunks")
View Source
var ErrHashNotSupported = errors.New("crypka: hash of given type is not supported")
View Source
var ErrInvalidAlgorithmType = errors.New("crypka: Invalid algorithm type")
View Source
var ErrInvalidDestinationType = errors.New("crypka: Invalid getter destintation type. Must be pointer to struct or interface")
View Source
var ErrKXInvalidDestination = errors.New("crypka: given KX destination buffer is not valid")
View Source
var ErrKXUnsupportedPart = errors.New("crypka: specified public or secret KX part is not supported by this algorithm")
View Source
var ErrKeyNotMarshalable = errors.New("crypka: Key is not marshallable")
View Source
var ErrKeyParseField = errors.New("crypka: filed to parse key")
View Source
var ErrNoSuchAlgorithm = errors.New("crypka: No such algorithm")
View Source
var ErrPasswordHashMismatch = errors.New("crypka: password hash does not match password given")
View Source
var ErrPasswordHashParamMismatch = errors.New("crpyka: given password hash has different parameters compared to hasher, so it can't be processed")
View Source
var ErrPasswordHashParseFiled = errors.New("crypka: filed to parse password hash")
View Source
var ErrPasswordHashUnknownAlgo = errors.New("crypka: given password hash is encoded using unsupported algorithm")
View Source
var ErrRNGInvalidSeed = errors.New("crypka: given RNG seed is not valid")
View Source
var ErrRNGOutOfEntropy = errors.New("crypka: given RNG ran out of entropy and can't generate random data anymore")
View Source
var ErrSignInvalid = errors.New("crypka: sign is invalid")
View Source
var GlobalRegistry = NewRegistry()

Functions

func GenerateReasonableRNGSeed

func GenerateReasonableRNGSeed(rng RNG, info RNGAlgoInfo) (seed []byte, err error)

Generates RNG seed which: 1. Is valid seed for RNG algo specified with info. 2. Is 32 bytes if it's valid value for rng. 3. Otherwise it's max allowed bytes.

Note: this method is shortcut, but it shouldn't be used in super-secure implementations, since it sometimes may yield too short RNG seeds. Note #2: Reasonable value of 32 bytes of seed may change in future.

func MarshalKey

func MarshalKey(key interface{}, w io.Writer) (err error)

func MarshalKeyToSlice

func MarshalKeyToSlice(key interface{}) (data []byte, err error)

func RegisterAES128GCM

func RegisterAES128GCM(reg Registry)

Registers AES128GCM ciphers with nonce coutner and rng

func RegisterEd25519

func RegisterEd25519(reg Registry, options RegisterEd25519Options)

func RegisterSTLHMACs

func RegisterSTLHMACs(reg Registry, options RegisterSTLHMACsOptions)

RegisterSTLHMACs *some* of STL HMACes into specified registry. If registry is nil then registers in global registry.

func RegisterSTLHashes

func RegisterSTLHashes(reg Registry)

RegisterSTLHashes *some* of STL hashes into specified registry. If registry is nil then registers in global registry.

Types

type AEADSymmEncAlgo

type AEADSymmEncAlgo struct {
	KeyLength   int
	NonceLength int

	NonceConfig NonceConfig

	AEADFactory func(key []byte) (aead cipher.AEAD, err error)
}

func (*AEADSymmEncAlgo) GenerateKey

func (algo *AEADSymmEncAlgo) GenerateKey(ctx KeyGenerationContext, rng RNG) (key EncSymmKey, err error)

func (*AEADSymmEncAlgo) GetInfo

func (algo *AEADSymmEncAlgo) GetInfo() EncAlgoInfo

func (*AEADSymmEncAlgo) ParseSymmEncKey

func (algo *AEADSymmEncAlgo) ParseSymmEncKey(ctx KeyParseContext, data []byte) (key EncSymmKey, err error)

type AlgorithmType

type AlgorithmType uint8
const (
	SymmEncAlgorithmType  AlgorithmType = 1
	AsymEncAlgorithmType  AlgorithmType = 2
	HashAlgorithmType     AlgorithmType = 3
	SymmSignAlgorithmType AlgorithmType = 4
	AsymSignAlgorithmType AlgorithmType = 5
	RNGAlgorithmType      AlgorithmType = 6
	KXAlgorithmType       AlgorithmType = 7
)

type AnyContext

type AnyContext = *Context

type Argon2PasswordHash added in v0.0.2

type Argon2PasswordHash struct {
	Name string
	Salt []byte
	Hash []byte

	Version int

	Time    uint32
	Memory  uint32
	Threads uint8
}

PHCPasswordHash encoded in PHC format

func (*Argon2PasswordHash) GetAlgo added in v0.0.2

func (h *Argon2PasswordHash) GetAlgo() string

func (*Argon2PasswordHash) Load added in v0.0.2

func (dh *Argon2PasswordHash) Load(r io.ByteReader) (err error)

func (*Argon2PasswordHash) Raw added in v0.0.2

func (h *Argon2PasswordHash) Raw() (res []byte, err error)

type Argon2PasswordHasher added in v0.0.2

type Argon2PasswordHasher struct {
	// Defaults to argon2id
	AlgoName string

	SaltLength uint32
	KeyLength  uint32

	Memory  uint32
	Time    uint32
	Threads uint8

	RNG RNG
}

func (*Argon2PasswordHasher) CheckPassword added in v0.0.2

func (h *Argon2PasswordHasher) CheckPassword(ctx PasswordHashContext, password, hash []byte) (err error)

func (*Argon2PasswordHasher) HashPassword added in v0.0.2

func (h *Argon2PasswordHasher) HashPassword(ctx PasswordHashContext, password, appendTo []byte) (res []byte, err error)

type BaseAlgorithmInfo

type BaseAlgorithmInfo struct {
	Type AlgorithmType

	// Is this algorithm cryptographically secure.
	// This may change if algorithm is discovered to be insecure.
	IsSecure bool
}

type BlankEncSymmAlgo

type BlankEncSymmAlgo struct {
}

WARNING: This algorithm is FOR TESTING ONLY. IT DOES NOTHING, IT JUST COPIES DATA!!! It turns out however, to be useful for testing.

func (*BlankEncSymmAlgo) GenerateKey

func (algo *BlankEncSymmAlgo) GenerateKey(ctx KeyGenerationContext, rng RNG) (sk EncSymmKey, err error)

func (*BlankEncSymmAlgo) GetInfo

func (algo *BlankEncSymmAlgo) GetInfo() EncAlgoInfo

func (*BlankEncSymmAlgo) ParseSymmEncKey

func (algo *BlankEncSymmAlgo) ParseSymmEncKey(ctx KeyParseContext, data []byte) (ek EncSymmKey, err error)

type CPKStreamSymmEncAlgo

type CPKStreamSymmEncAlgo struct {
	EncSymmAlgo
}

Implements algorithm, which handles streamming encryption in crypka's format.

func (*CPKStreamSymmEncAlgo) GenerateKey

func (algo *CPKStreamSymmEncAlgo) GenerateKey(ctx KeyGenerationContext, rng RNG) (key EncSymmKey, err error)

func (*CPKStreamSymmEncAlgo) GetInfo

func (algo *CPKStreamSymmEncAlgo) GetInfo() EncAlgoInfo

func (*CPKStreamSymmEncAlgo) ParseSymmEncKey

func (algo *CPKStreamSymmEncAlgo) ParseSymmEncKey(ctx KeyParseContext, data []byte) (key EncSymmKey, err error)

type CompressSigningKey

type CompressSigningKey struct {
	Compressor   SigningKey
	ActualSigner func(ctx KeyContext, data []byte) (sign []byte, err error)
}

func (*CompressSigningKey) MakeSigner

func (k *CompressSigningKey) MakeSigner(ctx KeyContext) (signer Signer, err error)

type CompressVerifier

type CompressVerifier struct {
	Ctx            KeyContext
	Compressor     Signer
	ActualVerifier func(ctx KeyContext, sign, data []byte) (err error)
}

func (*CompressVerifier) Verify

func (s *CompressVerifier) Verify(sign []byte) (err error)

func (*CompressVerifier) Write

func (s *CompressVerifier) Write(data []byte) (sz int, err error)

type CompressVerifyingKey

type CompressVerifyingKey struct {
	Compressor     SigningKey
	ActualVerifier func(ctx KeyContext, sign, data []byte) (err error)
}

func (*CompressVerifyingKey) MakeVerifier

func (k *CompressVerifyingKey) MakeVerifier(ctx KeyContext) (verifier Verifier, err error)

type Context

type Context struct {
	RNG              RNG
	SetInsecureTaint bool
}

func MakeDefaultContext

func MakeDefaultContext() *Context

type CounterNonceManager

type CounterNonceManager struct {
	Nonce  []byte
	Unsafe bool
}

CounterNonceManager is preallocated slice of specified size, which can be efficiently incremented by one in order to produce unique nonces for data encryption.

NOTE: THIS IS NOT CONSTANT TIME!!! Be aware that this counter leaks(or may leak) count of chunks encrypted already. Usually this is not problem, since attacker knows anyway how many chunks were encrypted.

func NewNonceCounterManager

func NewNonceCounterManager(sz int, unsafe bool) *CounterNonceManager

func (CounterNonceManager) GetNonce

func (nm CounterNonceManager) GetNonce() []byte

func (CounterNonceManager) Len

func (nm CounterNonceManager) Len() int

Len retuns size of nonce generated by this nonce counter.

func (CounterNonceManager) NextNonce

func (nm CounterNonceManager) NextNonce() (err error)

Increment assigns next unique value to this nonce counter. If it's not possible without overflowing or changing nonce size then error is returned.

type CryptoRNGAlgo

type CryptoRNGAlgo struct {
}

RNG which uses crypto/rand.Reader to provide RNG.

func (*CryptoRNGAlgo) GetInfo

func (algo *CryptoRNGAlgo) GetInfo() RNGAlgoInfo

func (*CryptoRNGAlgo) MakeRng

func (algo *CryptoRNGAlgo) MakeRng(ctx RNGGenerationContext, seed []byte) (rng RNG, err error)

type DecKey

type DecKey interface {
	MakeDecryptor(ctx KeyContext) (Decryptor, error)
}

type Decryptor

type Decryptor interface {
	GetEncInfo() EncInfo

	Decrypt(in, appendTo []byte) (res []byte, err error)
	Finalize() (err error)
}

type DefaultStructHashWriter added in v0.0.2

type DefaultStructHashWriter struct {
}

Note: this writer does not differnciate empty and nil slice, just like golang STL in functions like len.

func (*DefaultStructHashWriter) WriteStruct added in v0.0.2

func (dsh *DefaultStructHashWriter) WriteStruct(ctx HashContext, res interface{}, w io.Writer) (err error)

type Ed25519SignAsymAlgo

type Ed25519SignAsymAlgo struct {
	Compressor SigningKey
}

Ed25519SignAsymAlgo, which uses compressor given to prevent buffering data before signing. This allows for easier signing of arbitrarily sized data.

func (*Ed25519SignAsymAlgo) GenerateKeyPair

func (a *Ed25519SignAsymAlgo) GenerateKeyPair(ctx KeyGenerationContext, rng RNG) (sk SigningKey, vk VerifyingKey, err error)

func (*Ed25519SignAsymAlgo) GetInfo

func (a *Ed25519SignAsymAlgo) GetInfo() SignAlgoInfo

func (*Ed25519SignAsymAlgo) ParseSigningKey

func (a *Ed25519SignAsymAlgo) ParseSigningKey(ctx KeyParseContext, key []byte) (sk SigningKey, err error)

func (*Ed25519SignAsymAlgo) ParseVerifyingKey

func (a *Ed25519SignAsymAlgo) ParseVerifyingKey(ctx KeyParseContext, key []byte) (vk VerifyingKey, err error)

type EncAlgo

type EncAlgo interface {
	GetInfo() EncAlgoInfo
}

type EncAlgoInfo

type EncAlgoInfo struct {
	BaseAlgorithmInfo
	EncInfo

	AuthMode EncAuthMode
}

type EncAsymAlgo

type EncAsymAlgo interface {
	EncAlgo
	EncAsymKeygen
	EncAsymKeyParser
}

type EncAsymKXAlgo

type EncAsymKXAlgo struct {
	EncSymmAlgo EncSymmAlgo
	KXAlgo      KXAlgo

	// Max size of ephemeral key length.
	// Ignored during encryption, used for decryption only.
	// Defaults to 1MB.
	MaxMarshaledEphemeralLength int

	// How many bytes should be loaded from KX.
	KXResultLength int

	// Optional, used to extend KX result to key.
	// Raw value used, if not present.
	// Value is truncated to as many bytes as needed by symmetric algo.
	RNGAlgo RNGAlgo

	// RNG to use to generate ephemeral keys.
	// One from context used if nil.
	EphemeralRNG RNG
}

EncAsymKXAlgo makes asymmetric encryption algorithm from symmetric encryption one and key exchange one. It's secure, unless used algorithms are secure. Since X25519 exists, it's preferred way to implement asymmetric encryption in application, when used along with ChaCha or AES.

func (*EncAsymKXAlgo) GenerateKeyPair

func (algo *EncAsymKXAlgo) GenerateKeyPair(ctx KeyGenerationContext, rng RNG) (ek EncKey, dk DecKey, err error)

func (*EncAsymKXAlgo) GetInfo

func (algo *EncAsymKXAlgo) GetInfo() EncAlgoInfo

func (*EncAsymKXAlgo) ParseDecKey

func (algo *EncAsymKXAlgo) ParseDecKey(ctx KeyParseContext, data []byte) (dk DecKey, err error)

func (*EncAsymKXAlgo) ParseEncKey

func (algo *EncAsymKXAlgo) ParseEncKey(ctx KeyParseContext, data []byte) (ek EncKey, err error)

type EncAsymKeyParser

type EncAsymKeyParser interface {
	ParseEncKey(ctx KeyParseContext, data []byte) (EncKey, error)
	ParseDecKey(ctx KeyParseContext, data []byte) (DecKey, error)
}

type EncAsymKeygen

type EncAsymKeygen interface {
	GenerateKeyPair(ctx KeyGenerationContext, rng RNG) (EncKey, DecKey, error)
}

type EncAuthMode

type EncAuthMode uint32

Note: rest of bits of this value is reserved for future use. They must not be used by any implementation.

const NotAuthenticatedEncAuthMode EncAuthMode = 0

func (*EncAuthMode) IsEagerAuthenticated

func (eam *EncAuthMode) IsEagerAuthenticated() bool

Returns true if decryptor will never yield data that differs from originally encrypted.

func (*EncAuthMode) IsFinalizeAuthetnicated

func (eam *EncAuthMode) IsFinalizeAuthetnicated() bool

Returns true, if decryptor will always detect changes made to ciphertext during finalization.

Note: this does not apply to block encryptors, since they by their nature are not finalizable, so according to above def, they should have it set to true.

func (*EncAuthMode) IsTruncAuthenticated

func (eam *EncAuthMode) IsTruncAuthenticated() bool

Retruns true, if decryptor will always detect if stream/chain encryption was truncated.

Note: this does not apply to block encryptors. They are never trunc authenticated, due to how they work.

Note 2: Truncation is checked during finalization only.

func (*EncAuthMode) IsZero

func (eam *EncAuthMode) IsZero() bool

func (*EncAuthMode) SetEagerAuthenticated

func (eam *EncAuthMode) SetEagerAuthenticated(to bool)

func (*EncAuthMode) SetFinalizeAuthetnicated

func (eam *EncAuthMode) SetFinalizeAuthetnicated(to bool)

func (*EncAuthMode) SetTruncAuthenticated

func (eam *EncAuthMode) SetTruncAuthenticated(to bool)

type EncInfo

type EncInfo struct {
	RequiresFinalization bool
	EncType              EncType
}

Note: this structure contains only basic information about encryption algorithm. In particular kind and if it requires finalization.

Note #2: this structure should contain only data, which is required to run encryption properly.

For more information about specified encryption scheme algorithm should be used.

type EncKey

type EncKey interface {
	MakeEncryptor(ctx KeyContext) (Encryptor, error)
}

type EncStreamRNGAlgo

type EncStreamRNGAlgo struct {
	CipherFactory           func(key []byte) (res cipher.Stream, err error)
	KeyLength               int
	ResedKeyLength          int // if zero, then no reseeding will happen
	CipherMaxGeneratedBytes uint64
}

RNG, which uses some stream encryption algorithm in order to generate random data from small seed. It automatically reseeds RNG when it's about to reach it's max generated bytes.

func (*EncStreamRNGAlgo) GetInfo

func (algo *EncStreamRNGAlgo) GetInfo() RNGAlgoInfo

func (*EncStreamRNGAlgo) MakeRng

func (algo *EncStreamRNGAlgo) MakeRng(ctx RNGGenerationContext, seed []byte) (rng RNG, err error)

type EncSymmAlgo

type EncSymmAlgo interface {
	EncAlgo
	EncSymmKeygen
	EncSymmKeyParser
}

type EncSymmKey

type EncSymmKey interface {
	EncKey
	DecKey
}

type EncSymmKeyParser

type EncSymmKeyParser interface {
	ParseSymmEncKey(ctx KeyParseContext, data []byte) (EncSymmKey, error)
}

type EncSymmKeygen

type EncSymmKeygen interface {
	GenerateKey(ctx KeyGenerationContext, rng RNG) (EncSymmKey, error)
}

type EncType

type EncType uint8

Defines relations between subsequent call to Encrypt/Decrypt functions. See specific types for more details.

const (
	// Block encryption encrypts(decrypts) each block atomically.
	// Blocks are independent of each other.
	//
	// Note: this should not be mistaken with block encryption from crypto world in general ie. fixed block size.
	// This one is more like AEAD encryption(think of box/sealedbox from nacl)
	EncTypeBlock EncType = 1

	// This kind of encryption requires that chunks passed for decryption are passed in same order(it MAY NOT be checked however)
	// that they were passed for encryption.
	//
	// Also no slicing is allowed. Each chunk yielded from encrypt must be passed in same and unmodified form to decrypt.
	EncTypeChain EncType = 2

	// It's just like EncTypeChain, but allows slicing. Passing partial chunks to decrypt is allowed.
	EncTypeStream EncType = 3
)

type Encryptor

type Encryptor interface {
	GetEncInfo() EncInfo

	Encrypt(in, appendTo []byte) (res []byte, err error)
	Finalize(appendTo []byte) (res []byte, err error)
}

type HMACSignAlgorithm

type HMACSignAlgorithm struct {
	Hash         crypto.Hash
	MinKeyLength int
	MaxKeyLength int
	GenKeyLength int
}

HMACSignAlgorithm wraps golang's stl HMAC type and makes it crypka's HMAC types.

func (*HMACSignAlgorithm) GenerateKey

func (a *HMACSignAlgorithm) GenerateKey(ctx KeyGenerationContext, rng RNG) (key SymmSignKey, err error)

func (*HMACSignAlgorithm) GetInfo

func (a *HMACSignAlgorithm) GetInfo() SignAlgoInfo

func (*HMACSignAlgorithm) ParseSymmSignKey

func (a *HMACSignAlgorithm) ParseSymmSignKey(ctx KeyGenerationContext, data []byte) (key SymmSignKey, err error)

type HashCompressRNGAlgo

type HashCompressRNGAlgo struct {
	Compressor    SigningKey
	InnerAlgo     RNGAlgo
	MinSeedLength int
}

Algorithm, which uses hash function to compress seed of arbitrary size into one appropriate for RNG. It's allowed for hash to return more data than RNG seed needs, but it must not yield less than required.

If provided more data than requried, then only part of hash is used.

func (*HashCompressRNGAlgo) GetInfo

func (algo *HashCompressRNGAlgo) GetInfo() RNGAlgoInfo

func (*HashCompressRNGAlgo) MakeRng

func (algo *HashCompressRNGAlgo) MakeRng(ctx RNGGenerationContext, seed []byte) (rng RNG, err error)

type HashContext added in v0.0.2

type HashContext = *Context

type HashSignAlgorithm

type HashSignAlgorithm struct {
	Hash crypto.Hash
}

HashSignAlgorithm wraps golang's stl hash type and makes it crypka's hash types.

func (*HashSignAlgorithm) GenerateKey

func (a *HashSignAlgorithm) GenerateKey(ctx KeyGenerationContext, rng RNG) (SymmSignKey, error)

func (*HashSignAlgorithm) GetInfo

func (a *HashSignAlgorithm) GetInfo() SignAlgoInfo

func (*HashSignAlgorithm) ParseSymmSignKey

func (a *HashSignAlgorithm) ParseSymmSignKey(ctx KeyParseContext, data []byte) (SymmSignKey, error)

type HashableHelper

type HashableHelper struct {
	W io.Writer
}

Provides a few extension functions, which HashableWriter does not have, but are useful when implementing.

func (*HashableHelper) EnterSlice added in v0.0.2

func (util *HashableHelper) EnterSlice(length int) (err error)

func (*HashableHelper) EnterStruct added in v0.0.2

func (util *HashableHelper) EnterStruct() (err error)

Note: this function is not called on top level struct

func (*HashableHelper) ExitSlice added in v0.0.2

func (util *HashableHelper) ExitSlice() (err error)

func (*HashableHelper) ExitStruct added in v0.0.2

func (util *HashableHelper) ExitStruct() (err error)

func (*HashableHelper) WriteByteSlice

func (util *HashableHelper) WriteByteSlice(data []byte) (err error)

func (*HashableHelper) WriteConstBytes added in v0.0.2

func (util *HashableHelper) WriteConstBytes(data []byte) (err error)

func (*HashableHelper) WriteInt

func (util *HashableHelper) WriteInt(v int) (err error)

func (*HashableHelper) WriteInt16

func (util *HashableHelper) WriteInt16(v int16) (err error)

func (*HashableHelper) WriteInt32

func (util *HashableHelper) WriteInt32(v int32) (err error)

func (*HashableHelper) WriteInt64

func (util *HashableHelper) WriteInt64(v int64) (err error)

func (*HashableHelper) WriteInt8

func (util *HashableHelper) WriteInt8(v int8) (err error)

func (*HashableHelper) WriteSlice

func (util *HashableHelper) WriteSlice(length int, writer func(hh *HashableHelper) (err error)) (err error)

Wrapper for enter and exit using function given.

func (*HashableHelper) WriteString

func (util *HashableHelper) WriteString(data string) (err error)

func (*HashableHelper) WriteStruct

func (util *HashableHelper) WriteStruct(writer func(hh *HashableHelper) (err error)) (err error)

Wrapper for enter and exit using function given.

func (*HashableHelper) WriteUint16

func (util *HashableHelper) WriteUint16(v uint16) (err error)

func (*HashableHelper) WriteUint32

func (util *HashableHelper) WriteUint32(v uint32) (err error)

func (*HashableHelper) WriteUint64

func (util *HashableHelper) WriteUint64(v uint64) (err error)

func (*HashableHelper) WriteUint8

func (util *HashableHelper) WriteUint8(v uint8) (err error)

func (*HashableHelper) WriteVarBytes added in v0.0.2

func (util *HashableHelper) WriteVarBytes(data []byte) (err error)

type HashableNew added in v0.0.2

type HashableNew interface {
	HashSelf(w *HashableHelper) (err error)
}

type KXAlgo

type KXAlgo interface {
	KXParser
	KXExchanger
	KXKeygen
	GetInfo() KXAlgorithmInfo
}

type KXAlgorithmInfo

type KXAlgorithmInfo struct {
	BaseAlgorithmInfo
	MaxResLen int
}

type KXExchanger

type KXExchanger interface {
	PerformExchange(ctx KeyContext, public KXPublic, secret KXSecret, res []byte) (err error)
}

type KXKeygen

type KXKeygen interface {
	GenerateKXPair(ctx KeyGenerationContext, rng RNG) (public KXPublic, secret KXSecret, err error)
}

type KXParser

type KXParser interface {
	ParseKXPublic(ctx KeyParseContext, data []byte) (KXPublic, error)
	ParseKXSecret(ctx KeyParseContext, data []byte) (KXSecret, error)
}

type KXPublic

type KXPublic interface {
}

type KXRngAlgo

type KXRngAlgo struct {
	KXAlgo
	RNGAlgo RNGAlgo

	RNGSeedBytes int
}

KX Algorithm, which expands result of KX using RNG. It uses RNGseedBytes if not zero. It uses maximum possible RNG seed size. If max size from both algorithms is infinite, then uses 64 bytes. Panics if RNG requires larger seed than KX algo is able to generate.

func (*KXRngAlgo) GetInfo

func (algo *KXRngAlgo) GetInfo() KXAlgorithmInfo

func (*KXRngAlgo) PerformExchange

func (algo *KXRngAlgo) PerformExchange(ctx KeyContext, public KXPublic, secret KXSecret, res []byte) (err error)

type KXSecret

type KXSecret interface {
}

type KeyContext

type KeyContext = *Context

type KeyGenerationContext

type KeyGenerationContext = *Context

type KeyParseContext

type KeyParseContext = *Context

type MarshalableKey

type MarshalableKey interface {
	MarshalToWriter(w io.Writer) (err error)
}

Represents key, which may be serialized. Key serialized in such way should be parsable by algorithm.

# Marshalling note Please note that keys shouldn't be marshalled in any other way. This is the only legit way, which provides security against leaking some redundant data.

type MathRNGAlgo

type MathRNGAlgo struct {
}

RNG which uses math/rand to provide RNG. It's not secure.

func (*MathRNGAlgo) GetInfo

func (algo *MathRNGAlgo) GetInfo() RNGAlgoInfo

func (*MathRNGAlgo) MakeRng

func (algo *MathRNGAlgo) MakeRng(ctx RNGGenerationContext, seed []byte) (rng RNG, err error)

type NonceConfig

type NonceConfig struct {
	NonceType NonceType

	// If true, disables all checks in encryptor, which prevent user from producing too many ciphertexts.
	AllowUnsafe bool
}

Defines how specified algoritm should manage nonce. Please note that changing it may change algorithm characteristics.

func (*NonceConfig) MakeNonceManager

func (config *NonceConfig) MakeNonceManager(ctx KeyContext, length int) (nm NonceManager, err error)

type NonceManager

type NonceManager interface {
	GetNonce() []byte
	NextNonce() (err error)
}

type NonceType

type NonceType uint8
const (
	// Instructs algorithm to use nonce counter to manage nonces.
	// Allows producing 2^(bytes of nonce) blocks.
	//
	// WARNING! After using this mode nothing should be encrypted with the same key.
	CounterNonce NonceType = 1

	// Instructs algorithm to use RNG to manage nonces.
	// Allows producing 2^(bytes of nonce / 2) blocks.
	//
	// WARNING when using multiple encryptors for encryption it's user responsibility not to exceed above number.
	// Note: some algorithms like XChaCha20 have nonce so big, that for any real world usage infinite amount of ciphertexts may be produced.
	RNGNonce NonceType = 2
)

type PHash added in v0.0.2

type PHash interface {
	GetAlgo() string // returns name of hashing algorithm used
	Raw() []byte     // returns encoded form of hash, so if it was parsed again, it would yield same result
}

type PHashAlgoInfo added in v0.0.2

type PHashAlgoInfo struct {
	Name   string
	Secure bool
}

type PHasher added in v0.0.2

type PHasher interface {
	GetInfo() PHashAlgoInfo
	HashPassword(ctx PasswordHashContext, password []byte, appendTo []byte) (res []byte, err error)
	CheckPassword(ctx PasswordHashContext, password, hash []byte) (err error)
}

PHasher are special kind of hashes. Rather than stream data, they accept constant-sized data and yield hash of it.

type Padder

type Padder interface {
	Pad(data []byte, msgSize int) []byte
}

Padder is something able to apply padding to message.

type PadderFunc

type PadderFunc func(data []byte, msgSize int) []byte

PadderFunc is function which is Padder.

func (PadderFunc) Pad

func (f PadderFunc) Pad(data []byte, msgSize int) []byte

Pad makes PadderFunc satisfy Padder.

type Padding

type Padding interface {
	Padder
	Unpadder
}

func PaddingIEC78164

func PaddingIEC78164() Padding

PaddingIEC78164 is single padding scheme, which has simple format: [any, any, any..., 0x80, 0x00, 0x00, 0x00...].

type PasswordHashContext added in v0.0.2

type PasswordHashContext = *Context

type RNG

type RNG interface {
	io.Reader
}

Base RNG type. Base RNG is simple reader. It may implement additional interfaces.

func ContextGetRNG

func ContextGetRNG(ctx *Context) RNG

func FallbackContextGetRNG

func FallbackContextGetRNG(ctx *Context, rng RNG) RNG

Returns given RNG or one from context in case given one was nil. Returns default RNG in case provided one was not set.

type RNGAlgo

type RNGAlgo interface {
	GetInfo() RNGAlgoInfo
	MakeRng(ctx RNGGenerationContext, seed []byte) (rng RNG, err error)
}

type RNGAlgoInfo

type RNGAlgoInfo struct {
	BaseAlgorithmInfo
	RNGType           RNGType
	MaxGeneratedBytes uint64 // 0 corresponds to infinite
	MinSeedLength     int    // 0 if no seed
	MaxSeedLength     int    // 0 if no seed, ^0 max value if unlimited
}

type RNGGenerationContext

type RNGGenerationContext = *Context

type RNGNonceManager

type RNGNonceManager struct {
	Nonce  []byte
	RNG    io.Reader
	Unsafe bool
	// contains filtered or unexported fields
}

func (*RNGNonceManager) GetNonce

func (nm *RNGNonceManager) GetNonce() []byte

func (*RNGNonceManager) Initialize

func (nm *RNGNonceManager) Initialize() (err error)

func (*RNGNonceManager) NextNonce

func (nm *RNGNonceManager) NextNonce() (err error)

type RNGType

type RNGType uint8
const (
	// RNG, which was created from some seed. It may generate finite amount of random data before looping.
	SeedRNGType RNGType = 1

	// RNG, which collects entropy from environment(most of the time os does that).
	// It generates infinite amount of random data and can't be constructed with seed.
	EnvRNGType RNGType = 2
)

type RegisterEd25519Options

type RegisterEd25519Options struct {
	CompressorData []struct {
		Suffix     string
		Compressor SigningKey
	}
}

type RegisterSTLHMACsOptions

type RegisterSTLHMACsOptions struct {
	MinKeyLength int
	GenKeyLength int
}

type Registry

type Registry interface {
	RegisterAlgo(name string, algo interface{})
	GetAlgo(name string) (algo interface{})
	Lock()

	GetAlgorithmTyped(name string, dstAlgo interface{}) (err error)
}

Registry for any kind of algorithm.

func NewRegistry

func NewRegistry() Registry

type SerializedKey

type SerializedKey struct {
	Algo string
	Type SerializedKeyType
	Data []byte
}

type SerializedKeyType

type SerializedKeyType uint8

type SignAlgo

type SignAlgo interface {
	GetInfo() SignAlgoInfo
}

type SignAlgoInfo

type SignAlgoInfo struct {
	BaseAlgorithmInfo
}

type SignAsymAlgo

type SignAsymAlgo interface {
	SignAlgo
	SignAsymKeyGen
	SignAsymKeyParser
}

type SignAsymKeyGen

type SignAsymKeyGen interface {
	GenerateKeyPair(ctx KeyGenerationContext, rng RNG) (SigningKey, VerifyingKey, error)
}

type SignAsymKeyParser

type SignAsymKeyParser interface {
	ParseSigningKey(ctx KeyParseContext, data []byte) (SigningKey, error)
	ParseVerifyingKey(ctx KeyParseContext, data []byte) (VerifyingKey, error)
}

type SignSymmAlgo

type SignSymmAlgo interface {
	SignAlgo
	SignSymmKeyGen
	SignSymmKeyParser
}

type SignSymmKeyGen

type SignSymmKeyGen interface {
	GenerateKey(ctx KeyGenerationContext, rng RNG) (SymmSignKey, error)
}

type SignSymmKeyParser

type SignSymmKeyParser interface {
	ParseSymmSignKey(ctx KeyParseContext, data []byte) (SymmSignKey, error)
}

type Signer

type Signer interface {
	io.Writer

	Finalize(appendTo []byte) ([]byte, error)
}

type SigningKey

type SigningKey interface {
	MakeSigner(key KeyContext) (Signer, error)
}

type StructHashWriter added in v0.0.2

type StructHashWriter interface {
	WriteStruct(ctx HashContext, data interface{}, w io.Writer) (err error)
}

StructHashWriter manages process of writing arbitrary typed data into writer.

Note: it's not correct to use this multiple times on same signer. Security guarantees do not hold then. Use slice of values instead.

type StructHasher added in v0.0.2

type StructHasher interface {
	HashStruct(ctx HashContext, data interface{}) (res []byte, err error)
}

StructHash consumes arbitrary input and produces hash from in form of byte slice.

Note: when this type is too narrow and it does not fit the use case(like signing), StructHashWriter should be preferred.

type StructHasherImpl added in v0.0.2

type StructHasherImpl struct {
	// Note: SK given *should* be hash.
	SigningKey SigningKey
	Writer     StructHashWriter // optional; default used if unset
}

func (*StructHasherImpl) HashStruct added in v0.0.2

func (sh *StructHasherImpl) HashStruct(ctx HashContext, data interface{}) (res []byte, err error)

type SymmSignKey

type SymmSignKey interface {
	SigningKey
	VerifyingKey
}

SymmSignKey even though, it at first sight may seem useless, its quite useful. Usually this is implemented by HMACs and hashers(in case of hashes key is always constant and zero-length, but abstraction still works).

type Unpadder

type Unpadder interface {
	// Unpad returns value < 0 if it failed
	Unpad(data []byte) (msgSize int)
}

Unpadder is something able to remove padding.

type UnpadderFunc

type UnpadderFunc func(data []byte) (msgSize int)

UnpadderFunc if cuntion which is Unpadder.

func (UnpadderFunc) Unpad

func (f UnpadderFunc) Unpad(data []byte) (msgSize int)

Unpad makes UnpadderFunc satisfy Unpadder.

type Verifier

type Verifier interface {
	io.Writer

	Verify(sign []byte) error
}

type VerifyingKey

type VerifyingKey interface {
	MakeVerifier(ctx KeyContext) (Verifier, error)
}

type X25519KXAlgo

type X25519KXAlgo struct{}

func (*X25519KXAlgo) GenerateKXPair

func (algo *X25519KXAlgo) GenerateKXPair(ctx KeyGenerationContext, rng RNG) (public KXPublic, secret KXSecret, err error)

func (*X25519KXAlgo) GetInfo

func (algo *X25519KXAlgo) GetInfo() KXAlgorithmInfo

func (*X25519KXAlgo) ParseKXPublic

func (algo *X25519KXAlgo) ParseKXPublic(ctx KeyParseContext, data []byte) (pub KXPublic, err error)

func (*X25519KXAlgo) ParseKXSecret

func (algo *X25519KXAlgo) ParseKXSecret(ctx KeyParseContext, data []byte) (sec KXSecret, err error)

func (*X25519KXAlgo) PerformExchange

func (algo *X25519KXAlgo) PerformExchange(ctx KeyContext, public KXPublic, secret KXSecret, res []byte) (err error)

type XorEncSymmAlgo

type XorEncSymmAlgo struct {
	MinKeyLength      int
	MaxKeyLength      int
	GenerateKeyLength int
}

WARNING: This algorithm is FOR TESTING ONLY. DO NOT USE IT IN PRODUCTION ANYTIME EVER!

func (*XorEncSymmAlgo) GenerateKey

func (algo *XorEncSymmAlgo) GenerateKey(ctx KeyGenerationContext, rng RNG) (sk EncSymmKey, err error)

func (*XorEncSymmAlgo) GetInfo

func (algo *XorEncSymmAlgo) GetInfo() EncAlgoInfo

func (*XorEncSymmAlgo) ParseSymmEncKey

func (algo *XorEncSymmAlgo) ParseSymmEncKey(ctx KeyParseContext, data []byte) (ek EncSymmKey, err error)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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