package tdesktop

import (
	
	
	 // #nosec G505
	

	
	

	
	
	
)

// See https://github.com/telegramdesktop/tdesktop/blob/v2.9.8/Telegram/SourceFiles/storage/details/storage_file_utilities.cpp#L322.
func (,  []byte) ( crypto.Key) {
	 := localEncryptNoPwdIterCount
	if len() > 0 {
		 = localEncryptIterCount
	}

	 := pbkdf2.Key(, , , len(), sha1.New)
	copy([:], )
	return 
}

// See https://github.com/telegramdesktop/tdesktop/blob/v2.9.8/Telegram/SourceFiles/storage/details/storage_file_utilities.cpp#L300.
func (,  []byte) ( crypto.Key) {
	 := 1
	if len() > 0 {
		 = kStrongIterationsCount
	}

	 := sha512.New()
	_, _ = .Write()
	_, _ = .Write()
	_, _ = .Write()

	 := pbkdf2.Key(.Sum(nil), , , len(), sha512.New)
	copy([:], )
	return 
}

// See https://github.com/telegramdesktop/tdesktop/blob/v2.9.8/Telegram/SourceFiles/storage/details/storage_file_utilities.cpp#L584.
func ( []byte,  crypto.Key) ([]byte, error) {
	if  := len(); %aes.BlockSize != 0 {
		return nil, errors.Errorf("invalid length %d, must be padded to 16", )
	}
	// Get encryptedKey.
	var  bin.Int128
	 := copy([:], )
	 = [:]

	,  := crypto.OldKeys(, , crypto.Server)
	,  := aes.NewCipher([:])
	if  != nil {
		return nil, errors.Wrap(, "create cipher")
	}

	 := make([]byte, len())
	ige.DecryptBlocks(, [:], , )

	if  := sha1.Sum(); !bytes.Equal([:16], [:]) /* #nosec G401 */ {
		return nil, errors.New("msg_key mismatch")
	}
	return , nil
}

// encryptLocal code may panic
func ( []byte,  crypto.Key) ([]byte, error) {
	if  := len(); %aes.BlockSize != 0 {
		return nil, errors.Errorf("invalid length %d, must be padded to 16", )
	}
	// Compute encryptedKey.
	var  bin.Int128
	 := sha1.Sum() // #nosec G401
	copy([:], [:])

	,  := crypto.OldKeys(, , crypto.Server)
	,  := aes.NewCipher([:])
	if  != nil {
		return nil, errors.Wrap(, "create cipher")
	}

	 := make([]byte, 16+len())
	copy(, [:])
	ige.EncryptBlocks(, [:], [16:], )

	return , nil
}