public static string Encrypt(string data, int key = 0) { if (data == null) { return(null); } if (string.IsNullOrEmpty(data)) { return(""); } int keyIndex = key; string nonce = Utility.GenerateNonce(NONCE_LENGTH); string toEncrypt = data + nonce; byte[] binary = Encoding.UTF8.GetBytes(toEncrypt); byte[] encrypted; AESCryptor.Encrypt(ref keyIndex, ref binary, out encrypted); string beEncrypted = StringTools.ToBase64String(encrypted); beEncrypted = keyIndex + Utility.SEP + beEncrypted + Utility.SEP + nonce; return(beEncrypted); }
public static string EncryptToString(byte[] data, int key = 0) { if (data == null) { return(null); } if (data.Length == 0) { return(string.Empty); } int keyIndex = key; string nonce = Utility.GenerateNonce(NONCE_LENGTH); byte[] binaryNonce = Encoding.UTF8.GetBytes(nonce); byte[] dataToEncrypt = Utility.MergeBytes(data, binaryNonce); byte[] encrypted; AESCryptor.Encrypt(ref keyIndex, ref dataToEncrypt, out encrypted); string beEncrypted = StringTools.ToBase64String(encrypted); beEncrypted = keyIndex + Utility.SEP + beEncrypted + Utility.SEP + nonce; return(beEncrypted); }
public void Write(Stream xOut, bool enc) { this.Body.Write(xOut); if (xOut.Length % 16 != 0) { while (xOut.Length % 16 != 0) { xOut.WriteByte(0x70); } } byte[] xoutBuf = new byte[xOut.Length]; xOut.Position = 0; xOut.Read(xoutBuf, 0, xoutBuf.Length); if (enc) { MemoryStream xMem = new MemoryStream(AESCryptor.Encrypt(xoutBuf, this.key)); xOut.SetLength(0); xOut.Write(xMem.ToArray(), 0, (int)xMem.Length); } else { xOut.SetLength(0); xOut.Write(xoutBuf, 0, xoutBuf.Length); } }
public void Test_Encrypt() { var result = AESCryptor.Encrypt("测试一下内容先", Key); Output.WriteLine(result); Assert.Equal("JWm0M2KzKwxe8ylzkfujgQkyEq+kG1ZVirENQqCl8BI=", result); }
public void Test_EncryptIv() { string iv = InitIv(16); Output.WriteLine(iv); var result = AESCryptor.Encrypt("测试一下内容先", Key, Encoding.UTF8, iv, 256, 128, CipherMode.CBC, PaddingMode.PKCS7); Output.WriteLine(result); Assert.Equal("JWm0M2KzKwxe8ylzkfujgV8i5XUnUaHOpY7MaND0Z3g=", result); }
public static byte[] BinaryEncrypt(byte[] data, int you_know_what_is_this_key = 0) { if (data == null) { return(null); } if (data.Length == 0) { return(data); } int keyIndex = you_know_what_is_this_key; byte[] encrypted; AESCryptor.Encrypt(ref keyIndex, ref data, out encrypted); return(encrypted); }