public void Decrypt_Missingkey() { string encryptedMessage = "njkP6V+HTbQW2a9nmtAtvnN70XEgWTWUypOMIMu1PtU="; ArgumentNullException exception = null; Exception otherException = null; byte[] salt = { 1, 2, 3, 4, 5, 6, 7, 8 }; //Act AESEncryptor encryptor = new AESEncryptor(salt, 1234); try { byte[] actualResult = encryptor.Decrypt(Convert.FromBase64String(encryptedMessage), 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"); }
private List <NodeCredential> GetAllNodeCredentials() { var credentialsList = new List <NodeCredential>(); // Create a settings file if not exists. if (!File.Exists(SETTINGS_FILE_PATH)) { File.CreateText(SETTINGS_FILE_PATH); } // Open the file to read from. using (StreamReader sr = File.OpenText(SETTINGS_FILE_PATH)) { string row; while ((row = sr.ReadLine()) != null) { var decryptedRow = _aESEncryptor.Decrypt(row); credentialsList.Add(new NodeCredential { Node = decryptedRow.Split(':')[0], Authorization = decryptedRow.Split(':')[1], }); } } return(credentialsList); }
private byte[] GetDecryptedBytes() { if (settings.encryptionType == ES2Settings.EncryptionType.AES128) // AES 128-bit encryption { AESEncryptor aesEncryptor = new AESEncryptor(settings.encryptionPassword, MoodkieSecurity.AESBits.BITS128); return(aesEncryptor.Decrypt(reader.ReadBytes(reader.ReadInt32()))); } else // XOR Obfuscation { return(Obfuscator.Obfuscate(reader.ReadBytes(reader.ReadInt32()), settings.encryptionPassword)); } }
public static byte[] DecryptBytes(byte[] bytes) { byte[] decrypted = null; try { string[] parts = Encoding.UTF8.GetString(Convert.FromBase64String(PKIV)).Split('/'); decrypted = AESEncryptor.Decrypt(KeyToBytes(parts[0]), KeyToBytes(parts[1]), bytes); } catch (Exception e) { Debug.LogError("GameDataUtils (DecryptBytes):: Error Dencrypting Bytes - " + e); } return(decrypted); }
public void Decrypt_Success() { string password = "******"; string encryptedMessage = "nQaemyTbqIii/fAy69BLYpo9jl64stTDlRNy4s1d8uM="; string expectedResult = "testing"; byte[] salt = { 1, 2, 3, 4, 5, 6, 7, 8 }; //Act AESEncryptor encryptor = new AESEncryptor(salt, 1234); byte[] actualResult = encryptor.Decrypt(Convert.FromBase64String(encryptedMessage), password); //Assert Assert.IsTrue(actualResult.AreEqual(expectedResult.ToBytes()), "Expected results to match"); }
public static string UnlockFileSafe(string safePath, SecureString password) { StreamReader dataReader = new StreamReader(safePath); string unlockDirectory = Path.GetFileNameWithoutExtension(safePath); while (!dataReader.EndOfStream) { string fileName = dataReader.ReadLine(); //File name decryption string decryptedName = Encoding.Unicode.GetString(AESEncryptor.Decrypt(UniqueHash.SecureHashString("1npr0gramsecretKey"), fileName)); string data = dataReader.ReadLine(); string path = unlockDirectory + "\\" + decryptedName.TrimEnd(); // path = "sample.png"; try { byte[] decryptedData = AESEncryptor.Decrypt(password, data); if (!Directory.Exists(unlockDirectory)) { Directory.CreateDirectory(unlockDirectory); } File.Create(path).Close(); File.WriteAllBytes(path, decryptedData); } catch (WrongPasswordException) { System.Console.WriteLine("A jelszo helytelen"); return("Failed"); } System.Console.WriteLine("Jelenleg: " + decryptedName); } System.Console.WriteLine("Befejezve"); dataReader.Dispose(); return("Sucbess"); }
/// <summary> /// 用户登录 /// </summary> /// <param name="name">用户账号</param> /// <param name="pw">密码</param> /// <returns></returns> public Result <AppUserEntity> Login(string name, string pw) { if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(pw)) { return(ResultUtil.Fail <AppUserEntity>(null, "用户名或密码不能为空")); } var entity = db.Load <AppUserEntity>(MySearchUtil.New() .AndEqual("IsDel", false) .AndEqual("Name", name)); if (entity == null || AESEncryptor.Decrypt(entity.Pw) != pw) { return(ResultUtil.Fail <AppUserEntity>(null, "用户名密码错误")); } else { return(ResultUtil.Success <AppUserEntity>(entity)); } }
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"); }
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"); }
/// <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()); } }
private ExecResult <TResult> ParseCenterResponse(string response) { var result = new ExecResult <TResult>(); var view = JsonConvert.DeserializeObject <ResponseView>(response); //解密 string encryptkey = RSAEncryptor.decryptData(view.encryptkey, XmlConfig.ReapalPrivateKeyPfxUrl); var data = AESEncryptor.Decrypt(view.data, encryptkey); var sData = JsonConvert.DeserializeObject <BaseView>(data); if (sData.result_code == "0000") { result.Success = true; } else { result.MsgCode = sData.result_code; result.Message = sData.result_msg; result.Success = false; } return(result); }
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"); }
public void ReadEntity(IDictionary <string, EntityProperty> properties, OperationContext operationContext) { #if RT IEnumerable <PropertyInfo> myProperties = entity.GetType().GetRuntimeProperties(); var classAttributes = System.Attribute.GetCustomAttributes(entity.GetType()); #else IEnumerable <PropertyInfo> myProperties = this.GetType().GetProperties(); var classAttributes = System.Attribute.GetCustomAttributes(this.GetType()); #endif EncryptionTicks = properties["EncryptionTicks"]?.Int64Value ?? -1; EncryptionKey keyAttribute = (EncryptionKey)classAttributes.FirstOrDefault(x => !((x as EncryptionKey)?.IsDefaultValue ?? true)); if (keyAttribute == null) { keyAttribute = (EncryptionKey)classAttributes.First(x => (x as EncryptionKey) != null); keyAttribute = keyAttribute ?? new EncryptionKey(24, 8, 3); } foreach (PropertyInfo property in myProperties) { // reserved properties if (property.Name == "PartitionKey" || property.Name == "RowKey" || property.Name == "Timestamp" || property.Name == "ETag" || property.Name == "EncryptionTicks") { continue; } // Enforce public getter / setter #if RT if (property.SetMethod == null || !property.SetMethod.IsPublic || property.GetMethod == null || !property.GetMethod.IsPublic) #else if (property.GetSetMethod() == null || !property.GetSetMethod().IsPublic || property.GetGetMethod() == null || !property.GetGetMethod().IsPublic) #endif { continue; } // only proceed with properties that have a corresponding entry in the dictionary if (!properties.ContainsKey(property.Name)) { continue; } EntityProperty entityProperty = properties[property.Name]; if (IsPropertyNull(entityProperty)) { property.SetValue(this, null, null); } else if (property.GetCustomAttribute(typeof(EncryptedProperty)) is EncryptedProperty encryptedAttribute) { object propValue = null; try { if (entityProperty.PropertyType == EdmType.String) { if (keyAttribute.isSingleKey) { using (var manager = new EncryptionManager(keyAttribute.Key)) { propValue = JsonConvert.DeserializeObject(AESEncryptor.Decrypt(entityProperty.StringValue, properties[property.Name + "IV"].StringValue), property.PropertyType); } } else { using (var manager = new EncryptionManager(keyAttribute.A, keyAttribute.B, keyAttribute.C)) { propValue = JsonConvert.DeserializeObject(manager.Decrypt(entityProperty.StringValue, properties[property.Name + "IV"].StringValue, EncryptionTicks), property.PropertyType); } } } } catch (Exception ex) { Console.Write(ex); } if (propValue != null) { property.SetValue(this, propValue, null); } else { switch (entityProperty.PropertyType) { case EdmType.String: if (property.PropertyType != typeof(string) && property.PropertyType != typeof(String)) { continue; } var propertyValue = AESEncryptor.Decrypt(entityProperty.StringValue, properties[property.Name + "IV"].StringValue); property.SetValue(this, propertyValue, null); break; case EdmType.Binary: if (property.PropertyType != typeof(byte[])) { continue; } var binaryValue = JsonConvert.DeserializeObject <byte[]>(AESEncryptor.Decrypt(entityProperty.StringValue, properties[property.Name + "IV"].StringValue)); property.SetValue(this, binaryValue, null); break; case EdmType.Boolean: if (property.PropertyType != typeof(bool) && property.PropertyType != typeof(Boolean) && property.PropertyType != typeof(Boolean?) && property.PropertyType != typeof(bool?)) { continue; } property.SetValue(this, entityProperty.BooleanValue, null); break; case EdmType.DateTime: if (property.PropertyType == typeof(DateTimeOffset)) { var dateValue = JsonConvert.DeserializeObject <DateTimeOffset>(AESEncryptor.Decrypt(entityProperty.StringValue, properties[property.Name + "IV"].StringValue)); property.SetValue(this, dateValue.UtcDateTime, null); } else if (property.PropertyType == typeof(DateTimeOffset)) { var dateValue = JsonConvert.DeserializeObject <DateTime>(AESEncryptor.Decrypt(entityProperty.StringValue, properties[property.Name + "IV"].StringValue)); property.SetValue(this, dateValue.ToUniversalTime(), null); } break; case EdmType.Double: if (property.PropertyType != typeof(double) && property.PropertyType != typeof(Double) && property.PropertyType != typeof(Double?) && property.PropertyType != typeof(double?)) { continue; } var doubleValue = JsonConvert.DeserializeObject <double>(AESEncryptor.Decrypt(entityProperty.StringValue, properties[property.Name + "IV"].StringValue)); property.SetValue(this, doubleValue, null); break; case EdmType.Guid: if (property.PropertyType != typeof(Guid) && property.PropertyType != typeof(Guid?)) { continue; } var guidValue = JsonConvert.DeserializeObject <Guid>(AESEncryptor.Decrypt(entityProperty.StringValue, properties[property.Name + "IV"].StringValue)); property.SetValue(this, guidValue, null); break; case EdmType.Int32: if (property.PropertyType != typeof(int) && property.PropertyType != typeof(Int32) && property.PropertyType != typeof(Int32?) && property.PropertyType != typeof(int?)) { continue; } var intValue = JsonConvert.DeserializeObject <int>(AESEncryptor.Decrypt(entityProperty.StringValue, properties[property.Name + "IV"].StringValue)); property.SetValue(this, intValue, null); break; case EdmType.Int64: if (property.PropertyType != typeof(long) && property.PropertyType != typeof(Int64) && property.PropertyType != typeof(long?) && property.PropertyType != typeof(Int64?)) { continue; } var intValue2 = JsonConvert.DeserializeObject <int>(AESEncryptor.Decrypt(entityProperty.StringValue, properties[property.Name + "IV"].StringValue)); property.SetValue(this, intValue2, null); break; } } } else { switch (entityProperty.PropertyType) { case EdmType.String: if (property.PropertyType != typeof(string) && property.PropertyType != typeof(String)) { continue; } property.SetValue(this, entityProperty.StringValue, null); break; case EdmType.Binary: if (property.PropertyType != typeof(byte[])) { continue; } property.SetValue(this, entityProperty.BinaryValue, null); break; case EdmType.Boolean: if (property.PropertyType != typeof(bool) && property.PropertyType != typeof(Boolean) && property.PropertyType != typeof(Boolean?) && property.PropertyType != typeof(bool?)) { continue; } property.SetValue(this, entityProperty.BooleanValue, null); break; case EdmType.DateTime: if (property.PropertyType == typeof(DateTime)) { property.SetValue(this, entityProperty.DateTimeOffsetValue.Value.UtcDateTime, null); } else if (property.PropertyType == typeof(DateTime?)) { property.SetValue(this, entityProperty.DateTimeOffsetValue.HasValue ? entityProperty.DateTimeOffsetValue.Value.UtcDateTime : (DateTime?)null, null); } else if (property.PropertyType == typeof(DateTimeOffset)) { property.SetValue(this, entityProperty.DateTimeOffsetValue.Value, null); } else if (property.PropertyType == typeof(DateTimeOffset?)) { property.SetValue(this, entityProperty.DateTimeOffsetValue, null); } break; case EdmType.Double: if (property.PropertyType != typeof(double) && property.PropertyType != typeof(Double) && property.PropertyType != typeof(Double?) && property.PropertyType != typeof(double?)) { continue; } property.SetValue(this, entityProperty.DoubleValue, null); break; case EdmType.Guid: if (property.PropertyType != typeof(Guid) && property.PropertyType != typeof(Guid?)) { continue; } property.SetValue(this, entityProperty.GuidValue, null); break; case EdmType.Int32: if (property.PropertyType != typeof(int) && property.PropertyType != typeof(Int32) && property.PropertyType != typeof(Int32?) && property.PropertyType != typeof(int?)) { continue; } property.SetValue(this, entityProperty.Int32Value, null); break; case EdmType.Int64: if (property.PropertyType != typeof(long) && property.PropertyType != typeof(Int64) && property.PropertyType != typeof(long?) && property.PropertyType != typeof(Int64?)) { continue; } property.SetValue(this, entityProperty.Int64Value, null); break; } } } }
/// <summary> /// 解密下载文件 /// </summary> /// <param name="encryptFileName">加密下载文件字符串</param> /// <returns>原始下载文件名称</returns> internal string DecryptFileName(string encryptFileName) { return(_fileEncryptor.Decrypt(encryptFileName)); }
public void DecryptTest() { string actual = _fileEncryptor.Decrypt("Eg6BUavJgIpZjY+qAZIcxA=="); Assert.AreEqual("Thunder.zip", actual); }
public Stream Decrypt(Stream encyptedData, bool readMode) { return(_encryptor.Decrypt(encyptedData, readMode)); }
/// <summary>Decrypt at file path</summary> /// <returns>Path to the decrypted file</returns> public FileInfo DecryptFile(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 fext = fi.Extension.TrimStart(new char[] { '.' }); // make sure valid file type if (!fext.Equals(Extension, StringComparison.InvariantCultureIgnoreCase)) { return(null); } // write to file - never overwrite using FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read); // 4 bytes - write a magic number - which is 'ray' followed by 0 byte[] magic = new byte[Magic.Length]; fs.Read(magic); if (!ArraysEqual(magic, Magic)) { return(null); } // 2 bytes - write the file format version which is 1.0 byte[] ver = new byte[Version.Length]; fs.Read(ver); // 16 bytes - first write the IV out which is 16 bytes byte[] iv = new byte[16]; fs.Read(iv); // 2 bytes - read a delimiator which is 01 byte[] delim = new byte[Delimiter.Length]; fs.Read(delim); // 1 byte - the length of the extension string byte[] ebl = new byte[1]; fs.Read(ebl); int el = Convert.ToInt32(ebl[0]); // read N bytes the original extension byte[] eb = new byte[el]; fs.Read(eb); string ext = Encoding.UTF8.GetString(eb); // 2 bytes - read a delimiator which is 01 fs.Read(delim); // 1 byte for the metadata size byte[] mdl = new byte[1]; fs.Read(mdl); // finally get the data itself int offset = 28 + el; byte[] data = new byte[fs.Length - offset]; fs.Read(data); // decrypt AESEncryptor enc = new AESEncryptor(); byte[] file = enc.Decrypt(data, this.Key, iv); enc.Clear(); string outPath = $"{dir}/{name}{this.Suffix}.{ext}"; File.WriteAllBytes(outPath, file); fs.Close(); return(new FileInfo(outPath)); }
public void DecryptFileTest() { string path = $"{IOHelpers.DesktopPath}/test.rayx"; // 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); // write to file - never overwrite using FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read); // 4 bytes - write a magic number - which is 'ray' followed by 0 byte[] magic = new byte[4]; fs.Read(magic, 0, 4); // 2 bytes - write the file format version which is 1.0 byte[] ver = new byte[2]; fs.Read(ver); // 16 bytes - first write the IV out which is 16 bytes byte[] iv = new byte[16]; fs.Read(iv); // 2 bytes - read a delimiator which is 01 byte[] delim = new byte[2]; fs.Read(delim); // 1 byte - the length of the extension string byte[] ebl = new byte[1]; fs.Read(ebl); int el = Convert.ToInt32(ebl[0]); // read N bytes the original extension byte[] eb = new byte[el]; fs.Read(eb); string ext = Encoding.UTF8.GetString(eb); // 2 bytes - read a delimiator which is 01 fs.Read(delim); // finally get the data itself int offset = 27 + el; byte[] data = new byte[fs.Length - offset]; fs.Read(data); // decrypt AESEncryptor enc = new AESEncryptor(); byte[] file = enc.Decrypt(data, key, iv); File.WriteAllBytes($"{IOHelpers.DesktopPath}/{name}-copy.{ext}", file); fs.Close(); Assert.IsTrue(file.Length > 0); }
public void DecryptTest() { string _actual = aesHelper.Decrypt("v4M1o7AhQ4EOVLxbs4ZIzQ=="); Assert.AreEqual("YanZhiwei", _actual); }
public LoadState LoadFromStream(Stream stream) { LoadState state = LoadState.Corrupted; try { byte[] decompressed = null; byte[] contentBytes = null; bool versionOkay = false; //Check version first int headerVersion = SaveUtilities.DeserializeVersion(stream); if (headerVersion == -1) { state = LoadState.Corrupted; } else if (headerVersion < HeaderVersion) { stream = UpgradeFile(stream); if (stream != null) { versionOkay = true; } else { state = LoadState.Corrupted; } } else if (headerVersion > HeaderVersion) { state = LoadState.VersionMismatch; } else { versionOkay = true; } if (versionOkay) { if (IsValidFile(stream, ref contentBytes)) { byte[] decrypted = AESEncryptor.Decrypt(m_cryptoKey, m_cryptoIV, contentBytes); if (decrypted != null) { decompressed = CLZF2.Decompress(decrypted); } else { Debug.LogError("SaveData :: Decryption failed!"); state = LoadState.Corrupted; } } else { Debug.LogError("SaveData :: File Corrupted!"); state = LoadState.Corrupted; } } if (decompressed != null) { using (MemoryStream jsonMemoryStream = new MemoryStream(decompressed)) { using (StreamReader reader = new StreamReader(jsonMemoryStream)) { if (m_saveData.FromJSON(reader)) { state = LoadState.OK; } else { Debug.LogWarning("Trying to load invalid JSON file at path: " + m_savePath); state = LoadState.Corrupted; } } } } } catch (Exception e) { //TODO determine exception types and see if any are recoverable! Debug.LogWarning("Exception when parsing file from stream"); Debug.LogWarning(e); } return(state); }