package crypto

import (
	

	

	

	
)

// DecryptFromBuffer decodes EncryptedMessage and decrypts it.
func ( Cipher) ( AuthKey,  *bin.Buffer) (*EncryptedMessageData, error) {
	 := &EncryptedMessage{}
	// Because we assume that buffer is valid during decrypting, we able to
	// use DecodeWithoutCopy and do not allocate inner buffer for EncryptedMessage.
	if  := .DecodeWithoutCopy();  != nil {
		return nil, 
	}

	return .Decrypt(, )
}

// Decrypt decrypts data from encrypted message using AES-IGE.
func ( Cipher) ( AuthKey,  *EncryptedMessage) (*EncryptedMessageData, error) {
	,  := .decryptMessage(, )
	if  != nil {
		return nil, 
	}

	 := .encryptSide.DecryptSide()
	// Checking SHA256 hash value of msg_key
	 := MessageKey(.Value, , )
	if  != .MsgKey {
		return nil, errors.New("msg_key is invalid")
	}

	 := &EncryptedMessageData{}
	// Notice: do not re-use plaintext, because we use DecodeWithoutCopy, it references
	// original buffer.
	if  := .DecodeWithoutCopy(&bin.Buffer{Buf: });  != nil {
		return nil, 
	}

	{
		// Checking that padding of decrypted message is not too big.
		const  = 1024
		 := int(.MessageDataLen)
		 := len(.MessageDataWithPadding) - 

		switch {
		case  < 0:
			return nil, errors.Errorf("message length is invalid: %d less than zero", )
		case %4 != 0:
			return nil, errors.Errorf("message length is invalid: %d is not divisible by 4", )
		case  > :
			return nil, errors.Errorf("padding %d of message is too big", )
		}
	}

	return , nil
}

// decryptMessage decrypts data from encrypted message using AES-IGE.
func ( Cipher) ( AuthKey,  *EncryptedMessage) ([]byte, error) {
	if .ID != .AuthKeyID {
		return nil, errors.New("unknown auth key id")
	}
	if len(.EncryptedData)%16 != 0 {
		return nil, errors.New("invalid encrypted data padding")
	}

	,  := Keys(.Value, .MsgKey, .encryptSide.DecryptSide())
	,  := aes.NewCipher([:])
	if  != nil {
		return nil, 
	}
	 := make([]byte, len(.EncryptedData))
	ige.DecryptBlocks(, [:], , .EncryptedData)

	return , nil
}