crypto

package
v0.0.0-...-87e9d67 Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2023 License: MIT Imports: 21 Imported by: 0

Documentation

Overview

Package crypto implements cryptographical primitives for MTproto.

Reference:

Index

Constants

View Source
const RSAKeyBits = 2048

RSAKeyBits is RSA key size.

Can be used as rsa.GenerateKey(src, RSAKeyBits).

Variables

This section is empty.

Functions

func CheckDH

func CheckDH(g int, p *big.Int) error

CheckDH performs DH parameters check described in Telegram docs.

Client is expected to check whether p is a safe 2048-bit prime (meaning that both p and (p-1)/2 are prime,
and that 2^2047 < p < 2^2048), and that g generates a cyclic subgroup of prime order (p-1)/2, i.e.
is a quadratic residue mod p. Since g is always equal to 2, 3, 4, 5, 6 or 7, this is easily done using quadratic
reciprocity law, yielding a simple condition on p mod 4g — namely, p mod 8 = 7 for g = 2; p mod 3 = 2 for g = 3;
no extra condition for g = 4; p mod 5 = 1 or 4 for g = 5; p mod 24 = 19 or 23 for g = 6; and p mod 7 = 3,
5 or 6 for g = 7.

See https://core.telegram.org/mtproto/auth_key#presenting-proof-of-work-server-authentication.

See https://core.telegram.org/api/srp#checking-the-password-with-srp.

See https://core.telegram.org/api/end-to-end#sending-a-request.

func CheckDHParams

func CheckDHParams(dhPrime, g, gA, gB *big.Int) error

CheckDHParams checks that g_a, g_b and g params meet key exchange conditions.

https://core.telegram.org/mtproto/auth_key#dh-key-exchange-complete

func CheckGP

func CheckGP(g int, p *big.Int) error

CheckGP checks whether g generates a cyclic subgroup of prime order (p-1)/2, i.e. is a quadratic residue mod p. Also check that g is 2, 3, 4, 5, 6 or 7.

This function is needed by some Telegram algorithms(Key generation, SRP 2FA).

See https://core.telegram.org/mtproto/auth_key.

See https://core.telegram.org/api/srp.

func DataWithHash

func DataWithHash(data []byte, randomSource io.Reader) ([]byte, error)

DataWithHash prepends data with SHA1(data) and 0..15 random bytes so result length is divisible by 16.

Use GuessDataWithHash(result) to obtain data.

func DecodeRSAPad

func DecodeRSAPad(data []byte, key *rsa.PrivateKey) ([]byte, error)

DecodeRSAPad implements server-side decoder of RSAPad.

func DecomposePQ

func DecomposePQ(pq *big.Int, randSource io.Reader) (p, q *big.Int, err error)

DecomposePQ decomposes pq into prime factors such that p < q.

func DecryptExchangeAnswer

func DecryptExchangeAnswer(data, key, iv []byte) (dst []byte, err error)

DecryptExchangeAnswer decrypts messages created during key exchange.

func DefaultRand

func DefaultRand() io.Reader

DefaultRand returns default entropy source.

func EncryptExchangeAnswer

func EncryptExchangeAnswer(rand io.Reader, answer, key, iv []byte) (dst []byte, err error)

EncryptExchangeAnswer encrypts messages created during key exchange.

func FillBytes

func FillBytes(b *big.Int, to []byte) bool

FillBytes is safe version of (*big.Int).FillBytes. Returns false if to length is not exact equal to big.Int's. Otherwise fills to using b and returns true.

func GuessDataWithHash

func GuessDataWithHash(dataWithHash []byte) []byte

GuessDataWithHash guesses data from data_with_hash.

func InRange

func InRange(x, min, max *big.Int) bool

InRange checks whether x is in (min, max) range, i.e. min < x < max.

func Keys

func Keys(authKey Key, msgKey bin.Int128, mode Side) (key, iv bin.Int256)

Keys returns (aes_key, aes_iv) pair for AES-IGE.

See https://core.telegram.org/mtproto/description#defining-aes-key-and-initialization-vector

Example:

key, iv := crypto.Keys(authKey, messageKey, crypto.Client)
cipher, err := aes.NewCipher(key[:])
if err != nil {
	return nil, err
}
encryptor := ige.NewIGEEncrypter(cipher, iv[:])

func MessageKey

func MessageKey(authKey Key, plaintextPadded []byte, mode Side) bin.Int128

MessageKey computes message key for provided auth_key and padded payload.

func NewSessionID

func NewSessionID(reader io.Reader) (int64, error)

NewSessionID generates new random int64 from reader.

Use crypto/rand.Reader if session id should be cryptographically safe.

func NonceHash1

func NonceHash1(newNonce bin.Int256, key Key) (r bin.Int128)

NonceHash1 computes nonce_hash_1. See https://core.telegram.org/mtproto/auth_key#dh-key-exchange-complete.

func OldKeys

func OldKeys(authKey Key, msgKey bin.Int128, mode Side) (key, iv bin.Int256)

OldKeys returns (aes_key, aes_iv) pair for AES-IGE.

See https://core.telegram.org/mtproto/description_v1#defining-aes-key-and-initialization-vector

Example:

key, iv := crypto.OldKeys(authKey, messageKey, crypto.Client)
cipher, err := aes.NewCipher(key[:])
if err != nil {
	return nil, err
}
encryptor := ige.NewIGEEncrypter(cipher, iv[:])

Warning: MTProto 1.0 is deprecated.

func ParseRSA

func ParseRSA(data []byte) (*rsa.PublicKey, error)

ParseRSA parses data RSA key in PKCS1 or PKIX forms.

func ParseRSAPublicKeys

func ParseRSAPublicKeys(data []byte) ([]*rsa.PublicKey, error)

ParseRSAPublicKeys parses data as list of PEM-encdoed public keys.

func Prime

func Prime(p *big.Int) bool

Prime checks that given number is prime.

func RSADecryptHashed

func RSADecryptHashed(data []byte, key *rsa.PrivateKey) ([]byte, error)

RSADecryptHashed decrypts given data with RSA.

func RSAEncryptHashed

func RSAEncryptHashed(data []byte, key *rsa.PublicKey, randomSource io.Reader) ([]byte, error)

RSAEncryptHashed encrypts given data with RSA, prefixing with a hash.

func RSAFingerprint

func RSAFingerprint(key *rsa.PublicKey) int64

RSAFingerprint returns fingerprint of RSA public key as defined in MTProto.

func RSAPad

func RSAPad(data []byte, key *rsa.PublicKey, randomSource io.Reader) ([]byte, error)

RSAPad encrypts given data with RSA, prefixing with a hash.

See https://core.telegram.org/mtproto/auth_key#presenting-proof-of-work-server-authentication.

func RSAPublicDecrypt

func RSAPublicDecrypt(pub *rsa.PublicKey, sig []byte) ([]byte, error)

RSAPublicDecrypt recovers the message digest from the raw signature using the signer’s RSA public key.

See also OpenSSL’s RSA_public_decrypt with RSA_NO_PADDING.

func RandInt128

func RandInt128(randSource io.Reader) (bin.Int128, error)

RandInt128 generates and returns new random 128-bit integer.

Use crypto/rand.Reader as randSource in production.

func RandInt256

func RandInt256(randSource io.Reader) (bin.Int256, error)

RandInt256 generates and returns new random 256-bit integer.

Use crypto/rand.Reader as randSource in production.

func RandInt64

func RandInt64(randSource io.Reader) (int64, error)

RandInt64 returns random int64 from randSource.

func RandInt64n

func RandInt64n(randSource io.Reader, n int64) (int64, error)

RandInt64n returns random int64 from randSource in [0; n).

func SHA256

func SHA256(from ...[]byte) []byte

SHA256 returns SHA256 hash.

func ServerSalt

func ServerSalt(newNonce bin.Int256, serverNonce bin.Int128) (salt int64)

ServerSalt computes server salt.

func TempAESKeys

func TempAESKeys(newNonce, serverNonce *big.Int) (key, iv []byte)

TempAESKeys returns tmp_aes_key and tmp_aes_iv based on new_nonce and server_nonce as defined in "Creating an Authorization Key".

Types

type AuthKey

type AuthKey struct {
	Value Key
	ID    [8]byte
}

AuthKey is a Key with cached id.

func (*AuthKey) DecodeJSON

func (a *AuthKey) DecodeJSON(d *jx.Decoder) error

DecodeJSON decode AuthKey from object with base64-encoded key and integer ID.

func (AuthKey) EncodeJSON

func (a AuthKey) EncodeJSON(e *jx.Encoder) error

EncodeJSON encodes AuthKey as object with base64-encoded key and integer ID.

func (AuthKey) IntID

func (a AuthKey) IntID() int64

IntID returns key fingerprint (ID) as int64.

func (AuthKey) MarshalJSON

func (a AuthKey) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (AuthKey) MarshalLogObject

func (a AuthKey) MarshalLogObject(encoder zapcore.ObjectEncoder) error

MarshalLogObject implements zap.ObjectMarshaler.

func (*AuthKey) SetIntID

func (a *AuthKey) SetIntID(v int64)

SetIntID sets key fingerprint (ID) as int64.

func (AuthKey) String

func (a AuthKey) String() string

String implements fmt.Stringer.

func (*AuthKey) UnmarshalJSON

func (a *AuthKey) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (AuthKey) Zero

func (a AuthKey) Zero() bool

Zero reports whether Key is zero value.

type Cipher

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

Cipher is message encryption utility struct.

func NewClientCipher

func NewClientCipher(rand io.Reader) Cipher

NewClientCipher creates new client-side Cipher.

func NewServerCipher

func NewServerCipher(rand io.Reader) Cipher

NewServerCipher creates new server-side Cipher.

func (Cipher) Decrypt

func (c Cipher) Decrypt(k AuthKey, encrypted *EncryptedMessage) (*EncryptedMessageData, error)

Decrypt decrypts data from encrypted message using AES-IGE.

func (Cipher) DecryptFromBuffer

func (c Cipher) DecryptFromBuffer(k AuthKey, buf *bin.Buffer) (*EncryptedMessageData, error)

DecryptFromBuffer decodes EncryptedMessage and decrypts it.

func (Cipher) Encrypt

func (c Cipher) Encrypt(key AuthKey, data EncryptedMessageData, b *bin.Buffer) error

Encrypt encrypts EncryptedMessageData using AES-IGE to given buffer.

func (Cipher) Rand

func (c Cipher) Rand() io.Reader

Rand returns random generator.

type EncryptedMessage

type EncryptedMessage struct {
	AuthKeyID [8]byte
	MsgKey    bin.Int128

	EncryptedData []byte
}

EncryptedMessage of protocol.

func (*EncryptedMessage) Decode

func (e *EncryptedMessage) Decode(b *bin.Buffer) error

Decode implements bin.Decoder.

func (*EncryptedMessage) DecodeWithoutCopy

func (e *EncryptedMessage) DecodeWithoutCopy(b *bin.Buffer) error

DecodeWithoutCopy is like Decode, but EncryptedData references to given buffer instead of copying.

func (EncryptedMessage) Encode

func (e EncryptedMessage) Encode(b *bin.Buffer) error

Encode implements bin.Encoder.

type EncryptedMessageData

type EncryptedMessageData struct {
	Salt                   int64
	SessionID              int64
	MessageID              int64
	SeqNo                  int32
	MessageDataLen         int32
	MessageDataWithPadding []byte

	// Message to encode to MessageDataWithPadding.
	// Needed to prevent unnecessary allocations in EncodeWithoutCopy.
	Message bin.Encoder
}

EncryptedMessageData is stored in EncryptedMessage.EncryptedData.

func (*EncryptedMessageData) Data

func (e *EncryptedMessageData) Data() []byte

Data returns message data without hash.

func (*EncryptedMessageData) Decode

func (e *EncryptedMessageData) Decode(b *bin.Buffer) error

Decode implements bin.Decoder.

func (*EncryptedMessageData) DecodeWithoutCopy

func (e *EncryptedMessageData) DecodeWithoutCopy(b *bin.Buffer) error

DecodeWithoutCopy is like Decode, but MessageDataWithPadding references to given buffer instead of copying.

func (EncryptedMessageData) Encode

func (e EncryptedMessageData) Encode(b *bin.Buffer) error

Encode implements bin.Encoder.

func (EncryptedMessageData) EncodeWithoutCopy

func (e EncryptedMessageData) EncodeWithoutCopy(b *bin.Buffer) error

EncodeWithoutCopy is like Encode, but tries to encode Message and uses only one buffer to encode. If Message is nil, fallbacks to Encode.

type Key

type Key [256]byte

Key represents 2048-bit authorization key value.

func (Key) AuxHash

func (k Key) AuxHash() [8]byte

AuxHash returns aux_hash value of key.

func (Key) ID

func (k Key) ID() [8]byte

ID returns auth_key_id.

func (Key) String

func (k Key) String() string

func (Key) WithID

func (k Key) WithID() AuthKey

WithID creates new AuthKey from Key.

func (Key) Zero

func (k Key) Zero() bool

Zero reports whether Key is zero value.

type Side

type Side byte

Side on which encryption is performed.

const (
	// Client side of encryption (e.g. messages from client).
	Client Side = 0
	// Server side of encryption (e.g. RPC responses).
	Server Side = 1
)

func (Side) DecryptSide

func (s Side) DecryptSide() Side

DecryptSide returns Side for decryption.

Directories

Path Synopsis
Package srp contains implementation of Secure Remote Password protocol.
Package srp contains implementation of Secure Remote Password protocol.

Jump to

Keyboard shortcuts

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