namespace PlaneGcsSdk.Contract.DtuClient
{
    /// <summary>
    /// 进行数据透传时利用随机码对MavLink数据包进行加密和解密的辅助类。
    /// </summary>
    public static class DataEncryptHelper
    {
        /// <summary>
        /// 对数据进行加密处理。
        /// </summary>
        /// <param name="data"></param>
        /// <param name="key">密钥</param>
        /// <param name="offset"></param>
        /// <param name="size"></param>
        public static void EncryptByKey(this byte[] data, byte key, int offset = 0, int size = -1)
        {
            int count;
            if (size == -1)
            {
                count = data.Length - offset;
            }
            else
            {
                count = size + offset;
            }
            for (var i = offset; i < count; i++)
            {
                //下面算法实现高低位调转
                var ch = data[i];
                ch >>= 4;
                data[i] <<= 4;
                data[i] |= ch;

                //根据Key进行异或处理
                //data[i] ^= key;
            }
        }

        /// <summary>
        /// 对数据进行解密处理。
        /// </summary>
        /// <param name="data"></param>
        /// <param name="key"></param>
        public static void DecryptByKey(this byte[] data, byte key, int offset = 0, int size = -1)
        {
            int count;
            if (size == -1)
            {
                count = data.Length - offset;
            }
            else
            {
                count = size + offset;
            }
            for (var i = offset; i < count; i++)
            {
                //根据Key进行异或处理
                //data[i] ^= key;

                //下面算法实现高低位调转
                var ch = data[i];
                ch >>= 4;
                data[i] <<= 4;
                data[i] |= ch;
            }
        }
    }
}
