/// <summary> /// 发送数据时,将字节数组加密 /// </summary> /// <param name="_bytes">[in] 字节数组</param> /// <param name="_key">[in] DES加密用的64位秘钥</param> /// <returns>加密后的Byte数组</returns> public static byte[] EncryptBytes(byte[] _bytes, string _key) { Debug.Assert(_key.Length == 8, "<EncryptBytes> key length must be 8."); Debug.Assert(_bytes.Length % 8 == 0, "<EncryptBytes> input byte array length must mod 8 == 0."); int batch_count = _bytes.Length / 8; byte[] ret = new byte[_bytes.Length]; MemoryStream ms = new MemoryStream(); Des obj = new Des(_key); for (int i = 0; i < batch_count; i++) { byte[] arr_plan_bytes = new byte[8]; byte[] arr_encrypted_bytes = new byte[8]; Array.Copy(_bytes, i * 8, arr_plan_bytes, 0, 8); BitArray bit_arr_plan = new BitArray(arr_plan_bytes); BitArray bit_arr_encrypted = obj.encrypt(bit_arr_plan); bit_arr_encrypted.CopyTo(arr_encrypted_bytes, 0); ms.Write(arr_encrypted_bytes, 0, 8); } ret = ms.ToArray(); ms.Close(); return(ret); }
static void Main(string[] args) { BinaryWriter bw = new BinaryWriter(new FileStream(@"D:\as.txt", FileMode.OpenOrCreate)); Des obj = new Des("T&^9c=A`"); string s = "To be or"; BitArray cipher = obj.encrypt(s); //PrintBitString(cipher); byte[] arr = new byte[cipher.Length / 8]; cipher.CopyTo(arr, 0); bw.Write(arr); bw.Close(); BitArray plain = obj.decrypt(cipher); //PrintBitString(plain); }