package crypto

import (
	
	

	

	
)

// countPadding returns the amount of random padding (in bytes) to append to a
// plaintext of length l before AES-IGE encryption.
//
// The padding both aligns the plaintext to the 16-byte block size (with at
// least 12 bytes of padding, as required by MTProto 2.0) and adds a random
// number of extra 16-byte blocks. The random component mirrors Telegram
// Desktop's CountPaddingPrimesCount and removes the deterministic
// encrypted-message length that would otherwise fingerprint the client.
//
// randByte provides the entropy for the random component; only its low 4 bits
// are used, yielding 0..15 extra 16-byte blocks (0..240 bytes).
func ( int,  byte) int {
	 := (16 - ( % 16)) % 16
	if  < 12 {
		 += 16
	}
	 += int(&0x0F) * 16
	return 
}

// encryptMessage encrypts plaintext using AES-IGE.
func ( Cipher) ( AuthKey,  *bin.Buffer) (EncryptedMessage, error) {
	 := len(.Buf)

	var  [1]byte
	if ,  := io.ReadFull(.rand, [:]);  != nil {
		return EncryptedMessage{}, 
	}
	.Buf = append(.Buf, make([]byte, countPadding(, [0]))...)
	if ,  := io.ReadFull(.rand, .Buf[:]);  != nil {
		return EncryptedMessage{}, 
	}

	 := MessageKey(.Value, .Buf, .encryptSide)
	,  := Keys(.Value, , .encryptSide)
	,  := aes.NewCipher([:])
	if  != nil {
		return EncryptedMessage{}, 
	}
	 := EncryptedMessage{
		AuthKeyID:     .ID,
		MsgKey:        ,
		EncryptedData: make([]byte, len(.Buf)),
	}
	ige.EncryptBlocks(, [:], .EncryptedData, .Buf)
	return , nil
}

// Encrypt encrypts EncryptedMessageData using AES-IGE to given buffer.
func ( Cipher) ( AuthKey,  EncryptedMessageData,  *bin.Buffer) error {
	.Reset()
	if  := .EncodeWithoutCopy();  != nil {
		return 
	}

	,  := .encryptMessage(, )
	if  != nil {
		return 
	}

	.Reset()
	if  := .Encode();  != nil {
		return 
	}

	return nil
}