public void Encrypt_MissingKey() { //Arrange string testData = "testing"; ArgumentNullException exception = null; Exception otherException = null; byte[] salt = { 1, 2, 3, 4, 5, 6, 7, 8 }; //Act AESEncryptor encryptor = new AESEncryptor(salt, 1234); try { encryptor.Encrypt(testData.ToBytes(), null); } catch (ArgumentNullException e) { exception = e; } catch (Exception e) { otherException = e; } //Assert Assert.IsNull(otherException, $"Was expecting an ArgumentNullException [{otherException}]"); Assert.IsNotNull(exception, "Was expecting an ArgumentNullException exception"); Assert.AreEqual(exception.ParamName, "password", "Was expecting exception to be for password parameter"); }
public static string CreateFileSafe(string path, SecureString password, string safeName) { string[] files = Directory.GetFiles(path); StreamWriter dataWriter = new StreamWriter(safeName + ".safe"); foreach (var file in files) { //File name encryption byte[] fileNameBytes = Encoding.Unicode.GetBytes(Path.GetFileName(file)); string fileName = AESEncryptor.Encrypt(UniqueHash.SecureHashString("1npr0gramsecretKey"), fileNameBytes); System.Console.WriteLine(Path.GetFileName(file)); byte[] fileData = File.ReadAllBytes(file); string encryptedData = AESEncryptor.Encrypt(password, fileData); dataWriter.WriteLine(fileName); dataWriter.WriteLine(encryptedData); dataWriter.Flush(); } System.Console.WriteLine("Befejezve"); dataWriter.Dispose(); return("Sucess"); }
public MemoryStream SaveToStream() { MemoryStream stream = null; string json = m_saveData.ToJSON(); //Compress the data using LZF compression byte[] compressed = null; using (MemoryStream compMemStream = new MemoryStream()) { using (StreamWriter writer = new StreamWriter(compMemStream, Encoding.UTF8)) { writer.Write(json); writer.Close(); compressed = CLZF2.Compress(compMemStream.ToArray()); } } if (compressed != null) { byte[] encrypted = AESEncryptor.Encrypt(m_cryptoKey, m_cryptoIV, compressed); if (encrypted != null) { stream = new MemoryStream(); //Write version and headers! byte[] version = SaveUtilities.SerializeVersion(HeaderVersion); stream.Write(version, 0, version.Length); byte[] header = SaveUtilities.SerializeHeader(m_modifiedTime, m_deviceName, SaveUtilities.CalculateMD5Hash(encrypted), encrypted.Length); stream.Write(header, 0, header.Length); //Write encrypted and compressed data to stream stream.Write(encrypted, 0, encrypted.Length); } } return(stream); }
public static byte[] EncryptBytes(byte[] bytes) { byte[] encrypted = null; string[] parts = Encoding.UTF8.GetString(Convert.FromBase64String(PKIV)).Split('/'); encrypted = AESEncryptor.Encrypt(KeyToBytes(parts[0]), KeyToBytes(parts[1]), bytes); return(encrypted); }
public void InvalidAESKeyCausesError() { Assert.Throws(typeof(CryptographicException), () => { var encryptor = new AESEncryptor(new byte[] { 20, 19, 29, 28, 13 }); var data = Encoding.UTF8.GetBytes("Test message of awesome"); var encypted = Convert.ToBase64String(encryptor.Encrypt(data)); }); }
public void EncryptFileTest() { string path = $"{IOHelpers.DesktopPath}/test.jpeg"; // get a handle to the file FileInfo fi = new FileInfo(path); if (!fi.Exists) { Assert.Fail("No file to test"); return; } // base file name string name = Path.GetFileNameWithoutExtension(fi.Name); string ext = fi.Extension.TrimStart(new char[] { '.' }); // 4.2 Gig limit or throws an exception byte[] data = File.ReadAllBytes(path); // encrypt AESEncryptor enc = new AESEncryptor(); CipherMessage results = enc.Encrypt(data, key); // write to file - never overwrite using FileStream fs = new FileStream($"{IOHelpers.DesktopPath}/{name}.rayx", FileMode.CreateNew, FileAccess.Write); // 4 bytes - write a magic number - which is 'ray' followed by 0 fs.Write(new byte[] { 0x72, 0x61, 0x79, 0x00 }); // 2 bytes - write the file format version which is 1.0 fs.Write(new byte[] { 0x01, 0x00 }); // 16 bytes - first write the IV out which is 16 bytes fs.Write(results.IV, 0, results.IV.Length); // 2 bytes - write a delimiator which is 01 fs.Write(new byte[] { 0x00, 0x01 }); // write the original extension which is 1+len byte[] eb = Encoding.UTF8.GetBytes(ext); byte[] ebl = BitConverter.GetBytes(eb.Length); fs.WriteByte(ebl[0]); fs.Write(eb); // 2 bytes - write a delimiator which is 01 fs.Write(new byte[] { 0x00, 0x01 }); // write the encrypted data fs.Write(results.CipherBytes, 0, results.CipherBytes.Length); // flush and close fs.Flush(); fs.Close(); Assert.IsTrue(results.CipherBytes.Length > 0); }
public JsonResult Create(IFormCollection collection) { var entity = new AppUserEntity(); TryUpdateModelAsync(entity); entity.Pw = AESEncryptor.Encrypt("123456"); var result = service.Create(entity, AppUser); return(Json(result)); }
public void can_encrypt_and_decrypt_using_aes() { var encryptor = new AESEncryptor("SBcvpEo21MnyWamdiPxf1O+kBKk53s5GWRnrv3JoUVQ=", "vLWsT81pAOlk7hKd4cyz5A=="); var encr = encryptor.Encrypt("some string"); var stringy = Convert.ToBase64String(encr); var decryptor = new AESDecryptor("SBcvpEo21MnyWamdiPxf1O+kBKk53s5GWRnrv3JoUVQ=", "vLWsT81pAOlk7hKd4cyz5A=="); var decr = decryptor.Decrypt(encr); decr.ShouldBe("some string"); }
public byte[] GetEncryptedBytes(string password) { if (settings.encryptionType == ES2Settings.EncryptionType.AES128) // AES 128-bit encryption { AESEncryptor aesEncryptor = new AESEncryptor(password, MoodkieSecurity.AESBits.BITS128); return(aesEncryptor.Encrypt((writer.BaseStream as MemoryStream).ToArray())); } else // XOR Obfuscation { return(Obfuscator.Obfuscate((writer.BaseStream as MemoryStream).ToArray(), password)); } }
/// <summary> /// 重置密码 /// </summary> /// <param name="id"></param> /// <returns></returns> public Result ResetPw(int id) { var entity = Load(id); if (entity == null || entity.IsDel) { return(ResultUtil.Fail("用户不存在或已被删除")); } string sql = "UPDATE [Base_User] SET Pw=@Pw WHERE Id=@Id"; var row = db.Execute(sql, new { Id = id, Pw = AESEncryptor.Encrypt("123456") }); return(row > 0 ? ResultUtil.Success() : ResultUtil.Fail()); }
public void Encrypt_AlternateSalt() { //Arrange string password = "******"; string testData = "testing"; string expectedResult = "8ZH453MWfrdkWyiYjscqH1tDSmLwDaq6Uvif1a3j7tg="; byte[] salt = { 2, 2, 2, 2, 2, 2, 2, 2 }; //Act AESEncryptor encryptor = new AESEncryptor(salt, 1234); byte[] encryptedBytes = encryptor.Encrypt(testData.ToBytes(), password); byte[] decryptedBytes = encryptor.Decrypt(encryptedBytes, password); //Assert Assert.AreEqual(expectedResult, Convert.ToBase64String(encryptedBytes), "Results mismatch"); Assert.AreEqual(testData, Encoding.UTF8.GetString(decryptedBytes), "Results mismatch"); }
/// <summary> /// 修改密码 /// </summary> /// <param name="id">用户ID</param> /// <param name="oldPw">原始密码</param> /// <param name="newPw">新密码</param> /// <returns></returns> public Result ChangePw(int id, string oldPw, string newPw) { var account = Load(id); if (account == null || account.IsDel) { return(ResultUtil.Fail("请求的数据不存在")); } if (AESEncryptor.Decrypt(account.Pw) != oldPw) { return(ResultUtil.Fail("原始密码错误")); } else { string sql = "UPDATE [Base_User] SET Pw=@Pw WHERE Id=@Id"; var row = db.Execute(sql, new { Id = id, Pw = AESEncryptor.Encrypt(newPw) }); return(row > 0 ? ResultUtil.Success() : ResultUtil.Fail()); } }
public void Encrypt_AlternateIterations() { //Arrange string password = "******"; string testData = "testing"; string expectedResult = "p+AAj9R/fsqLKgoefdfbZCqgIUrLZOZvLET4ZOBfLcY="; byte[] salt = { 1, 2, 3, 4, 5, 6, 7, 8 }; //Act AESEncryptor encryptor = new AESEncryptor(salt, 2000); byte[] encryptedBytes = encryptor.Encrypt(testData.ToBytes(), password); byte[] decryptedBytes = encryptor.Decrypt(encryptedBytes, password); //Assert Assert.AreEqual(expectedResult, Convert.ToBase64String(encryptedBytes), "Results mismatch"); Assert.AreEqual(testData, Encoding.UTF8.GetString(decryptedBytes), "Results mismatch"); }
public void Encrypt_Success() { //Arrange string password = "******"; string expectedResult = "nQaemyTbqIii/fAy69BLYpo9jl64stTDlRNy4s1d8uM="; string testData = "testing"; byte[] salt = { 1, 2, 3, 4, 5, 6, 7, 8 }; //Act AESEncryptor encryptor = new AESEncryptor(salt, 1234); byte[] actualResult = encryptor.Encrypt(testData.ToBytes(), password); //Assert Assert.AreEqual(CipherMode.CBC, encryptor.CipherMode, "Mismatched CypherMode"); Assert.AreEqual(PaddingMode.PKCS7, encryptor.PaddingMode, "Mismatched PaddingMode"); Assert.AreEqual(expectedResult, Convert.ToBase64String(actualResult), "Results mismatch"); }
public void Serialize_Encrypt_RoundTrip() { List <KeyValuePair <string, string> > dictionary = new List <KeyValuePair <string, string> >(); dictionary.Add(new KeyValuePair <string, string>("first", "one")); string key = "12345678901234567890123456789012"; byte[] salt = { 1, 2, 3, 4, 5, 6, 7, 8 }; GenericBinarySerializer <List <KeyValuePair <string, string> > > serializer = new GenericBinarySerializer <List <KeyValuePair <string, string> > >(); AESEncryptor encryptor = new AESEncryptor(salt, 1234); //Act byte[] serializedData = serializer.Serialize(dictionary); byte[] encryptedData = encryptor.Encrypt(serializedData, key); byte[] decryptedData = encryptor.Decrypt(encryptedData, key); List <KeyValuePair <string, string> > deserializedData = serializer.DeSerialize(decryptedData); Assert.IsTrue(serializedData.AreEqual(decryptedData), "Was expecting serialized and decrypted data to be equal"); Assert.AreEqual(dictionary.Count, deserializedData.Count, "Was expecting dictionaries to have 1 entry"); }
private IDictionary <string, string> PrepareRequest() { var parameters = PrepareRequestCore(); string json = JsonConvert.SerializeObject(parameters); //加密业务数据--用AES对称加密算法 string AESKey = AESEncryptor.GenerateAESKey(); string strData = AESEncryptor.Encrypt(json, AESKey); //加密AESKey--用RSA非对称加密算法 string strKey = RSAEncryptor.encryptData(AESKey, XmlConfig.ReapalPublicKeyCerUrl); string timestamps = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); //var dic = new Dictionary<string, object>(); //dic.Add("merchant_id", ReapalMerchantId); //dic.Add("data", json); //dic.Add("encryptkey", strKey); //dic.Add("timestamp", timestamps); var dic = new Dictionary <string, object>(); dic.Add("merchant_id", "100000000239166"); dic.Add("data", "{\"cert_no\":\"412722199310223521\", \"face_id\":\"201709306319733661130403840\",\"cert_name\":\"孙晨杨\"}"); dic.Add("encryptkey", "Cii0jhBrt2plxhT9r1Tl5YiG/Q++uNmBMGXROtfE39Tj3coIYKyybIHQm42NQv5wUN8ajexoAaeykzp+lNsX5dUavKr9Ch8gxpSJpX0+C6xrSHWF3EVxJ8Y/i9DP00/D4Bw+PoWs63JTmEcDiaqIZ5IU8LvGjygpaTnZ7+Ntn2d3OM3wYAZtnX+cHwDRYC7/kJi+Ezwf4UHJj8EKqa0+y8pACqh4k2x9StjF5AhhkWB5pPWlOXFljQcXhMeQgnPgwHVX1cGVFYSADeM7IAAmVVT6BWkGf+GWPIUdeiXrFk0l1qvenyH6UWgo/SXuLm85x+toV5XD9uaiADg4XDpN+A=="); dic.Add("timestamp", "20170930112521148"); IDictionary <string, string> dicCollection = new SortedDictionary <string, string>(); dicCollection.Add("merchant_id", ReapalMerchantId); dicCollection.Add("data", strData); dicCollection.Add("encryptkey", strKey); dicCollection.Add("timestamp", timestamps); //dicCollection.Add("sign", Common.Sign(dic, XmlConfig.ReapalPrivateKeyPfxUrl)); dicCollection.Add("sign", "123456"); dicCollection.Add("sign_type", "RSA"); return(dicCollection); }
public void EncryptTest() { string actual = _fileEncryptor.Encrypt("Thunder.zip"); Assert.AreEqual("Eg6BUavJgIpZjY+qAZIcxA==", actual); }
public Stream Encrypt(Stream data, bool readMode) { return(_encryptor.Encrypt(data, readMode)); }
/// <summary>Encrypt the file at file path</summary> /// <returns>Path to the newly encrypted file</returns> public FileInfo EncryptFile(string path) { if (String.IsNullOrWhiteSpace(path)) { return(null); } // get a handle to the file FileInfo fi = new FileInfo(path); if (!fi.Exists) { return(null); } // base file name string dir = fi.DirectoryName; string name = Path.GetFileNameWithoutExtension(fi.Name); string ext = fi.Extension.TrimStart(new char[] { '.' }); // 4.2 Gig limit or throws an exception byte[] data = File.ReadAllBytes(path); // encrypt AESEncryptor enc = new AESEncryptor(); CipherMessage results = enc.Encrypt(data, this.Key); // remove the orginal from memory enc.Clear(); // write to file - never overwrite string outPath = $"{dir}/{name}.{Extension}"; using FileStream fs = new FileStream(outPath, FileMode.CreateNew, FileAccess.Write); // 4 bytes - write a magic number - which is 'ray' followed by 0 fs.Write(Magic); // 2 bytes - write the file format version which is 1.0 fs.Write(Version); // 16 bytes - first write the IV out which is 16 bytes fs.Write(results.IV, 0, results.IV.Length); // 2 bytes - write a delimiator which is 01 fs.Write(Delimiter); // write the original extension which is 1+len byte[] eb = Encoding.UTF8.GetBytes(ext); byte[] ebl = BitConverter.GetBytes(eb.Length); fs.WriteByte(ebl[0]); fs.Write(eb); // 2 bytes - write a delimiator which is 01 fs.Write(Delimiter); // 1 byte - later add a metadata section of optional data but for now its just 1 byte of value 0 fs.WriteByte(0x00); // write the encrypted data fs.Write(results.CipherBytes, 0, results.CipherBytes.Length); // flush and close fs.Flush(); fs.Close(); return(new FileInfo(outPath)); }
public void EncryptTest() { string _actual = aesHelper.Encrypt("YanZhiwei"); Assert.AreEqual("v4M1o7AhQ4EOVLxbs4ZIzQ==", _actual); }
/// <summary> /// 加密下载文件 /// </summary> /// <param name="fileName">需要下载文件名称</param> /// <returns>加密后的文件</returns> public string EncryptFileName(string fileName) { return(HttpUtility.UrlEncode(_fileEncryptor.Encrypt(fileName))); }
private string EncryptNodeCredentials(NodeCredential nodeCredential) { var row = $"{nodeCredential.Node.ToIdentity().ToString()}:{nodeCredential.Authorization}"; return(_aESEncryptor.Encrypt(row)); }
public async Task <ActionResult> Upload(IFormFile zip) { try { if (HttpContext.Request.Form != null && HttpContext.Request.Form.Files != null && HttpContext.Request.Form.Files[0] != null) { var file = HttpContext.Request.Form.Files[0]; if (file.ContentType == "application/zip") { string extractPath = "./" + file.FileName; Dictionary <string, TreeNode> mappings = new Dictionary <string, TreeNode>(); using (var stream = file.OpenReadStream()) using (ZipArchive archive = new ZipArchive(stream)) { if (Directory.Exists(extractPath)) { Helper.DeleteDirectory(extractPath); } archive.ExtractToDirectory(extractPath); TreeNode root = Helper.ListDirectory(_AESEncryptor, extractPath); string payload = JsonConvert.SerializeObject(root); byte[] byteArr = _AESEncryptor.Encrypt(payload); using (var httpClientHandler = new HttpClientHandler()) { httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return(true); }; using (var httpclient = new HttpClient(httpClientHandler)) { // var results = await httpclient.PostAsJsonAsync("https://localhost:5200/api/files", payload); httpclient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( "Basic", Convert.ToBase64String( System.Text.ASCIIEncoding.ASCII.GetBytes( $"{HttpContext.Request.Form["username"]}:{HttpContext.Request.Form["password"]}"))); var results = await httpclient.PostAsJsonAsync("https://localhost:5200/api/files", byteArr); string resultsContent = await results.Content.ReadAsStringAsync(); return(Ok(resultsContent)); } } } // using (var stream = file.OpenReadStream()) // using (ZipArchive archive = new ZipArchive(stream)) { // foreach (ZipArchiveEntry item in archive.Entries) { // var nestedFiles = item.FullName.Split("/", StringSplitOptions.RemoveEmptyEntries); // bool isDir = item.FullName.EndsWith("/") ? true : false; // // is dir, save them in mappings // if (isDir) { // var parentName = nestedFiles[0] + "/"; // if (!mappings.ContainsKey(parentName)) { // mappings.Add(parentName, new TreeNode { // parent = "root", // name = parentName, // children = new Dictionary<string, TreeNode>() // }); // } // if (nestedFiles.Length > 1) { // for (int i = 0; i < nestedFiles.Length - 1; i++) { // var childParentName = nestedFiles[i] + "/"; // var childFileName = nestedFiles[i + 1] + "/"; // if (childFileName == "assets/") { // Console.WriteLine("weoriu"); // } // TreeNode child = new TreeNode { name = childFileName, parent = childParentName }; // TreeNode targetParent = null; // for (int j = i; j > 0; j--) { // targetParent = mappings[parentName].Search(nestedFiles[j] + "/"); // if (targetParent != null) break; // } // if (targetParent == null) { // targetParent = mappings[parentName].Search(nestedFiles[i] + "/"); // } // if (targetParent != null && !targetParent.children.ContainsKey(childFileName)) { // targetParent.children.Add(childFileName, // new TreeNode { // name = childFileName, // parent = parentName, // children = new Dictionary<string, TreeNode>() // }); // } // } // } // } // // is file // else { // if (nestedFiles.Length == 1) { // if (!mappings.ContainsKey(nestedFiles[0])) { // mappings.Add(nestedFiles[0], new TreeNode { // name = nestedFiles[0], // parent = "root", // children = new Dictionary<string, TreeNode>() // }); // } // } else { // var parentName = nestedFiles[0] + "/"; // if (!mappings.ContainsKey(parentName)) { // mappings.Add(parentName, new TreeNode { // parent = "root", // name = parentName, // children = new Dictionary<string, TreeNode>() // }); // } // for (int i = 0; i < nestedFiles.Length - 1; i++) { // var childParentName = nestedFiles[i] + "/"; // var childFileName = nestedFiles[i + 1]; // if (i + 1 < nestedFiles.Length - 1) { // childFileName += "/"; // } // TreeNode child = new TreeNode { name = childFileName, parent = childParentName }; // TreeNode targetParent = null; // for (int j = i; j >= 0; j--) { // targetParent = mappings[parentName].Search(nestedFiles[j] + "/"); // if (targetParent != null) break; // } // if (targetParent == null) { // targetParent = mappings[parentName].Search(nestedFiles[i] + "/"); // } // if (targetParent != null && !targetParent.children.ContainsKey(childFileName)) { // targetParent.children.Add(childFileName, // new TreeNode { // name = childFileName, // parent = childParentName, // children = new Dictionary<string, TreeNode>() // }); // } // } // } // } // // has no parent dir, and is a file/or empty dir, add as is // } // string output = JsonConvert.SerializeObject(mappings); // return output; // } } } } catch (Exception ex) { Console.WriteLine("Exception: {0}", ex.ToString()); } return(Content("Some error occurred")); }