private void bEncrypted_Click(object sender, EventArgs e) { if (Check()) { CreateCryptoProvider(); //= NewFileName(file, 0); if (fileType == FileType.txt) { string text = richTextBox1.Text; byte[] bytes = Encoding.Unicode.GetBytes(text); //File.ReadAllBytes(file); byte[] encText = cryptoProvider.Encrypt(bytes); string encT = Convert.ToBase64String(encText); //Encoding.Unicode.GetString(encText); richTextBox1.Text = encT; //File.WriteAllText(saveFileName, encT, Encoding.Unicode); //cryptoProvider.Encrypt(file, NewFileName(file, 0)); } else { byte[] bytes = ImageToBytes(imageIn as Bitmap); byte[] encryptionBytes = cryptoProvider.Encrypt(bytes); imageOut = BytesToImage(encryptionBytes, imageIn.Size); pbImage.Image = imageOut; //imageOut.Save(saveFileName); } labelLog.ForeColor = Color.Green; labelLog.Text = "Зашифровано!"; StartTimer(); } }
public EntryKeyValuePairSerializationContract(EntryKeyValuePair entryKeyValuePair, ICipher cipher) { Key = cipher.Encrypt(entryKeyValuePair.Key); Value = cipher.Encrypt(entryKeyValuePair.Value); IsMultiline = entryKeyValuePair.IsMultiline; IsMandatory = entryKeyValuePair.IsMandatory; IsProtected = entryKeyValuePair.IsProtected; }
public UserDto ValidateUser(BaseDto user) { var result = userRepository.GetUser(user.Username, _cipher.Encrypt(user.Password, _settings.Value.AppKey)); if (result == null) { throw new UnauthorizedAccessException("Usuario y contraseña no validos"); } return(entityMapper.Map <User, UserDto>(result)); }
private void bEncrypt_Click(object sender, EventArgs e) { try { InitCipher(); byte[] bytes = Encoding.Unicode.GetBytes(tbPlainText.Text); byte[] encryptedBytes = cipher.Encrypt(bytes); tbEnctyptedText.Text = Convert.ToBase64String(encryptedBytes); } catch (Exception ex) { lError.Text = ex.Message; } }
/// <summary> /// RPC调用 /// </summary> /// <param name="name"></param> /// <param name="val"></param> /// <returns></returns> public static object Action(string name, string val, ICipher algorithm = null) { if (algorithm == null) { algorithm = Program.AES; } var encData = algorithm.Encrypt(val); var respJson = session.Post(UAC_API, new { action = name, data = encData }); if (respJson != null) { var jObj = respJson as JObject; if (jObj["data"][0] == null) { return(null); } var rtData = algorithm.Decrypt(jObj["data"][0].ToString()); var json = Program.JsonParse(rtData); if (json == null) { // 是字符串 return(rtData); } else { return(json); } } return(null); }
public override void Write(byte[] buf, int offset, int count) { EnsureStreamNotDisposed(); while (count > 0) { var nbytes = (count < 65535) ? count : 65535; var data = new byte[nbytes]; for (int i = 0; i < nbytes; i++) { data[i] = buf[offset++]; } var enc = (Cipher != null) ? Cipher.Encrypt(data) : data; if (enc.Length != data.Length) { throw new StreamControlException("Invalid Encrypted Block Length"); } //if (Logger.IsDebugEnabled) // Logger.Debug(">> Data: {0}", string.Join(" ", enc.Select(m => $"{m:x2}"))); _stream.Write(enc, 0, enc.Length); count -= nbytes; } }
public static Result <InvalidDataException> Encrypt(Stream input, Stream output, string password, IKdf kdf, ICipher cipher) { var key = kdf.Derive(password.ToUtf8Bytes(), cipher.RequiredKeyLen); try { var iv = Random.Bytes(32); var props = kdf.Properties; props["cipher"] = cipher.CipherName; props["iv"] = iv.ToBase64(); var propsBytes = JsonConvert.SerializeObject(props).ToUtf8Bytes(); var checksum = Sha256(propsBytes); var checksumDict = new Dictionary <string, object> { ["algo"] = "sha256", ["checksum"] = checksum.ToBase64(), }; var checksumBytes = JsonConvert.SerializeObject(checksumDict).ToUtf8Bytes(); output.Write(MagicHeader); output.Write(propsBytes); output.Write(checksumBytes); cipher.Encrypt(input, output, key, iv); } finally { Array.Clear(key, 0, key.Length); } return(Result <InvalidDataException> .Success); }
/// <summary> /// Encrypt the cleartext contents of a byte array /// </summary> /// <param name="cipher">The <see cref="ICipher"/> to use for encrypting the data</param> /// <param name="input">The cleartext data to encrypt</param> /// <returns>An array containing the encrypted data</returns> public static byte[] Encrypt(this ICipher cipher, byte[] input) { using (var ostream = new MemoryStream()) { cipher.Encrypt(input, ostream); return(ostream.ToArray()); } }
public void CipherPlainTextProperlyTest(ICipher cipher) { var plainText = "Secret Text"; var passPhrase = "password1"; var cipherText = cipher.Encrypt(plainText, passPhrase); Assert.True(plainText != cipherText); }
public void CipherAndDecipherTextTest(ICipher cipher) { var plainText = "Secret Text"; var passPhrase = "password1"; var cipherText = cipher.Encrypt(plainText, passPhrase); var decipherText = cipher.Decrypt(cipherText, passPhrase); Assert.True(plainText == decipherText); }
/// <summary> /// Authenticate/login user on the basis of given user name and password /// </summary> /// <param name="userName">Name of the user.</param> /// <param name="password">The password.</param> /// <returns>Sign in result</returns> public async Task <UsersDTO> Login(string userName, string password) { UsersDTO users = new UsersDTO(); var userId = string.Empty; string encryptPassword = _cipher.Encrypt(password); var resilt = await _userRepository.GetUserDetailByEmailId(userName); var user = _mapper.Map <UsersDTO>(resilt); userId = user != null?user.Id.ToString() : null; var result = string.IsNullOrEmpty(userId) ? false : await _accountRepository.Login(userId, encryptPassword); if (result && !string.IsNullOrEmpty(userId)) { users = user; } return(users); }
public static byte[] Encrypt( this ICipher cipher, ushort data) { if (cipher == null) { throw new ArgumentNullException(nameof(cipher)); } return(cipher.Encrypt(ToByteArray.Convert(data))); }
public static Task EncryptToFileAsync(this ICipher cipher, string file, string text, bool writeBase64 = false) { if (writeBase64) { return(Task.Run(() => File.WriteAllText(file, cipher.EncryptToBase64(text)))); } else { return(Task.Run(() => File.WriteAllBytes(file, cipher.Encrypt(text)))); } }
/// <summary> /// Encrypts the <paramref name="data"/>. /// </summary> /// <param name="cipher">The cipher.</param> /// <param name="data">The data to be encrypted.</param> /// <returns>The encrypted text.</returns> /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="cipher"/> is <see langword="null"/>.</exception> public static byte[] Encrypt( this ICipher cipher, int data) { if (cipher == null) { throw new ArgumentNullException(nameof(cipher)); } return(cipher.Encrypt(BitConverter.GetBytes(data))); }
public void Store(string title, string password, string superPassword) { var sign = cipher.CalculateHash(superPassword); var cipherPassword = cipher.Encrypt(password, superPassword); var record = new VaultRecord { Title = title, CipherPassword = cipherPassword, Sign = sign }; vault.Store(record); }
public static byte[] EncryptText( this ICipher cipher, string data) { if (cipher == null) { throw new ArgumentNullException(nameof(cipher)); } if (data == null) { throw new ArgumentNullException(nameof(data)); } return(cipher.Encrypt(data)); }
/// <summary> /// Encrypts the <paramref name="data"/> with the specified <paramref name="cipher"/>. /// </summary> /// <typeparam name="T">The type of the data to be encrypted.</typeparam> /// <param name="cipher">The cipher.</param> /// <param name="data">The data to be encrypted.</param> /// <returns>The encrypted data.</returns> public static byte[] EncryptNullable <T>( this ICipher cipher, T?data) where T : struct { if (cipher == null) { throw new ArgumentNullException(nameof(cipher)); } if (!EncryptTypedData.ContainsKey(typeof(T))) { throw new ArgumentException("The specified data type cannot be converted.", nameof(data)); } return(cipher.Encrypt(ToByteArray.ConvertNullable(data))); }
/// <summary> /// Add User /// </summary> /// <param name="userDetails"></param> /// <returns></returns> public async Task <bool> AddUser(UsersDTO userDetails) { if (userDetails.UserId == null) { userDetails.Password = _cipher.Encrypt(userDetails.Password); var response = await _userRepository.AddUser(_mapper.Map <UsersDTO, Users>(userDetails)); return(true); } else { userDetails.Id = ObjectId.Parse(userDetails.UserId); await _userRepository.UpdateUser(_mapper.Map <UsersDTO, Users>(userDetails)); return(true); } }
/// <summary> /// Encrypts the properties and fields in the specified grouping. /// </summary> /// <param name="g">The grouping which properties and fields should be encrypted.</param> void Encrypt( IGrouping <string, MemberInfo> g) { // build a JObject var jo = new JObject(); foreach (var mi in g) { var pi = mi as PropertyInfo; var fi = pi != null ? null : mi as FieldInfo; jo.Add(pi != null ? new JProperty(pi.Name, pi.GetValue(_instance)) : new JProperty(fi.Name, fi.GetValue(_instance))); } // serialize the JObject to JSON string var json = jo.ToString(); string decryptedJsonString; // if the new JSON is the same as the cached JSON - no need for encryption. if (_decryptedJsonStrings.TryGetValue(g.Key, out decryptedJsonString) && json == decryptedJsonString) { return; } // encrypt the JSON var piEncrypted = _type.GetProperty(g.Key, EncryptedPartsFlags); var fiEncrypted = piEncrypted != null ? null : _type.GetField(g.Key, EncryptedPartsFlags); var newValue = _cipher.Encrypt(json); // set the value of the EncryptedIn property or field if (piEncrypted != null) { piEncrypted.SetValue(_instance, newValue); } else { fiEncrypted.SetValue(_instance, newValue); } }
//public void RLEDecode() //{ // byte[] data = stream.ToArray(); // using (MemoryStream ms = new MemoryStream()) // { // using (BinaryWriter b = new BinaryWriter(ms)) // { // for (int i = 0; i < data.Length; i++) // { // if (data[i] != 144) // { // b.Write((byte)data[i]); // continue; // } // byte cnt = data[++i]; // i++; // if (cnt == 0) // b.Write((byte)144); // else // { // for (int c = 0; c < cnt; c++) // b.Write((byte)data[i]); // } // } // } // } //} //public void RLEEncode() //{ // byte[] data; // lock (stream) // data = stream.ToArray(); // bool finish = false; // using (MemoryStream ms = new MemoryStream()) // { // using (BinaryWriter bw = new BinaryWriter(ms)) // { // byte count = 1; // for (int i = 0; i < data.Length; i++) // { // if (i < data.Length - 1) // { // if (data[i] == data[i + 1] && count < 255) // count++; // else // finish = true; // } // else // finish = true; // if (finish) // { // finish = false; // if (count == 1) // { // if (data[i] == 144) // { // bw.Write(data[i]); // bw.Write((byte)0); // } // else // bw.Write(data[i]); // } // else // { // bw.Write((byte)144); // bw.Write((byte)count); // bw.Write(data[i]); // count = 1; // } // } // } // } // byte[] compressed = ms.ToArray(); // lock (stream) // { // stream.SetLength(0); // stream.Write(compressed, 0, compressed.Length); // } // } //} public byte[] ToByteArray(ICipher cipher) { using (MemoryStream data = new MemoryStream()) { using (BinaryWriter data_writer = new BinaryWriter(data)) { byte[] body = stream.ToArray(); if (cipher != null) { cipher.Encrypt(ref body, body.Length); } data_writer.Write(CodePacketType(type, body.Length)); data_writer.Write((int)body.Length); data_writer.Write(body, 0, (int)body.Length); return(data.ToArray()); } } }
/// <summary> /// Serializes the message and encrypts it with a given cipher. /// </summary> public void Serialize(ICipher cipher, out List <byte[]> results, out List <byte[]> hashes) { // results = new List <byte[]>(); hashes = new List <byte[]>(); // serialize Serialize(out var plains); // encrypt foreach (var plain in plains) { if (!cipher.Encrypt(plain, out var result, out var hash)) { throw new InvalidOperationException($"Unable to encrypt {Id} message: {BitConverter.ToString(plain).Replace("-", "")}"); } results.Add(result); hashes.Add(hash); } }
public static string EncryptData64( this ICipher cipher, byte[] data) { if (cipher == null) { throw new ArgumentNullException(nameof(cipher)); } if (data == null) { throw new ArgumentNullException(nameof(data)); } var base64 = cipher.Base64Encoded; cipher.Base64Encoded = false; var encryptedText = Convert.ToBase64String(cipher.Encrypt(data)); cipher.Base64Encoded = base64; return(encryptedText); }
public void Encrypt(int message, int key) { int cipherText = _cipher.Encrypt(message, key); _writer.WriteLine(string.Format(format, message, key, cipherText, nameof(Encrypt))); }
/// <summary> /// Encrypt the cleartext contents of a byte array and write the contents to an output stream /// </summary> /// <param name="cipher">The <see cref="ICipher"/> to use for encrypting the data</param> /// <param name="input">The cleartext data to encrypt</param> /// <param name="output">The output stream to write the encrypted data to</param> /// <remarks>This method leave the <paramref name="output"/> stream open</remarks> public static void Encrypt(this ICipher cipher, byte[] input, Stream output) { using (var istream = new MemoryStream(input)) cipher.Encrypt(istream, output); }
public string GenerateTicket(AuthenticationInfo authenticationInfo, string userUniqueID) { return(CipherService.Encrypt(SettingsManager.AppPrefix, userUniqueID, authenticationInfo, SettingsManager.TicketDurationTimeSpan)); }
/// <summary> /// Thread-safe. /// </summary> public static string EncryptToBase64(this ICipher cipher, string text) { return(Convert.ToBase64String(cipher.Encrypt(text))); }
/// <summary> /// Thread-safe. /// </summary> public static byte[] Encrypt(this ICipher cipher, string text) { return(cipher.Encrypt(Encoding.UTF8.GetBytes(text))); }
public IActionResult Encrypt([FromBody] string payload) { var result = _cipher.Encrypt(payload); return(Ok(result)); }
public void Encrypt(List <dynamic> key) { CipherText = cipher.Encrypt(PlainText, key); }
private void PerformEncrypt(ICipher cipher) { textBoxOutput.Text = cipher.Encrypt(textBoxInput.Text.PrepareText()).ToUpper(); }