Search Results

Search found 21 results on 1 pages for 'rijndaelmanaged'.

Page 1/1 | 1 

  • ASP.NET 2.0 RijndaelManaged encryption algorithm vs. FIPS

    - by R Rush
    I'm running into an issue with an ASP.NET 2.0 application. Our network folks just upped our security, and now I get the floowing error whenever I try to access the app: "This implementation is not part of the Windows Platform FIPS validated cryptographic algorithms." I've done a little research, and it sounds like ASP.NET uses the RijndaelManaged AES encryption algorithm to encrypt the ViewState of pages... and RijndaelManaged is on the list of algorithms that aren't FIPS compliant. We're certainly not explicitly calling any encryption algorithm... much less anything on the non-compliant list. This ViewState business makes sense to me, I guess. The thing I can't muddle out, though, is what to do about it. I've found a KB article that suggests using a web.config setting to specify a different algorithm... but either that didn't stick, or that algorithm isn't up to snuff, either. So: 1) Is the RijndaelManaged / ViewState thing actually the problem? Or am I barking up the wrong tree? 2) How to I specify what algorithm to use instead of RijndaelManaged? I've got a list of algorithms that are and aren't compliant; I'm just not sure where to plug that information in. Thanks! Richard

    Read the article

  • AesManaged and RijndaelManaged

    - by xscape
    Im currently developing a Silverlight application that connects to an old webservice. Our old webservice uses an encryption tool which silverlight does not support. Finally, we decided to used AesManaged for encryption, however, our webservice does not support AesManaged. Is their a way to decrypt an AesManaged to RijndaelManaged? If yes, can you please post a sample snippet? Your feedback is highly needed. Thank you.

    Read the article

  • RijndaelManaged: IV Generation?

    - by cam
    I want to implement the most secure, and most reliable form of symmetric key cryptography in my application. The user should input a password to encrypt/decrypt, and that's all. For RijndaelManaged, one must enter a key and an IV. I'm not sure how to address the situation. Right now, I have the entered password being hashed by SHA256 and then being used as the key for the Rijndael. What do I use for the IV? Another password?

    Read the article

  • Rijndael managed: plaintext length detction

    - by sheepsimulator
    I am spending some time learning how to use the RijndaelManaged library in .NET, and developed the following function to test encrypting text with slight modifications from the MSDN library: Function encryptBytesToBytes_AES(ByVal plainText As Byte(), ByVal Key() As Byte, ByVal IV() As Byte) As Byte() ' Check arguments. If plainText Is Nothing OrElse plainText.Length <= 0 Then Throw New ArgumentNullException("plainText") End If If Key Is Nothing OrElse Key.Length <= 0 Then Throw New ArgumentNullException("Key") End If If IV Is Nothing OrElse IV.Length <= 0 Then Throw New ArgumentNullException("IV") End If ' Declare the RijndaelManaged object ' used to encrypt the data. Dim aesAlg As RijndaelManaged = Nothing ' Declare the stream used to encrypt to an in memory ' array of bytes. Dim msEncrypt As MemoryStream = Nothing Try ' Create a RijndaelManaged object ' with the specified key and IV. aesAlg = New RijndaelManaged() aesAlg.BlockSize = 128 aesAlg.KeySize = 128 aesAlg.Mode = CipherMode.ECB aesAlg.Padding = PaddingMode.None aesAlg.Key = Key aesAlg.IV = IV ' Create a decrytor to perform the stream transform. Dim encryptor As ICryptoTransform = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV) ' Create the streams used for encryption. msEncrypt = New MemoryStream() Using csEncrypt As New CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write) Using swEncrypt As New StreamWriter(csEncrypt) 'Write all data to the stream. swEncrypt.Write(plainText) End Using End Using Finally ' Clear the RijndaelManaged object. If Not (aesAlg Is Nothing) Then aesAlg.Clear() End If End Try ' Return the encrypted bytes from the memory stream. Return msEncrypt.ToArray() End Function Here's the actual code I am calling encryptBytesToBytes_AES() with: Private Sub btnEncrypt_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEncrypt.Click Dim bZeroKey As Byte() = {&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0} PrintBytesToRTF(encryptBytesToBytes_AES(bZeroKey, bZeroKey, bZeroKey)) End Sub However, I get an exception thrown on swEncrypt.Write(plainText) stating that the 'Length of the data to encrypt is invalid.' However, I know that the size of my key, iv, and plaintext are 16 bytes == 128 bits == aesAlg.BlockSize. Why is it throwing this exception? Is it because the StreamWriter is trying to make a String (ostensibly with some encoding) and it doesn't like &H0 as a value?

    Read the article

  • RijndaelManaged Padding when data matches block size

    - by trampster
    If I use PKCS7 padding in RijndaelManaged with 16 bytes of data then I get 32 bytes of data output. It appears that for PKCS7 when the data size matches the block size it adds a whole extra block of data. If I use Zeros padding for 16 bytes of data I get out 16 bytes of data. So for Zeros padding if the data matches the block size then it doesn't pad. I have searched through the documentation and it says nothing about this difference in padding behavior. Can someone please point me to some kind of documentation which specifies what the padding behavior should be for the different padding modes when the data size matches the block size.

    Read the article

  • Specified key is not a valid size for this algorithm...

    - by phenevo
    Hi, I have with this code: RijndaelManaged rijndaelCipher = new RijndaelManaged(); // Set key and IV rijndaelCipher.Key = Convert.FromBase64String("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz012345678912"); rijndaelCipher.IV = Convert.FromBase64String("1234567890123456789012345678901234567890123456789012345678901234"); I get throws : Specified key is not a valid size for this algorithm. Specified initialization vector (IV) does not match the block size for this algorithm. What's wrong with this strings ? Can I count at some examples strings from You ?

    Read the article

  • Encrypting Files with AES, Encrypting Key with RSA - Am I on the right track?

    - by Shawn Steward
    Overview: I'm trying to design an application that will encrypt files to safely send through the mail. I'm planning on using AES/RijndaelManaged encryption from .Net to encrypt the files initially, using a randomly generated key using RNGCryptoServiceProvider. I'm then encrypting this random AES key with a RSA Public key. The receiver of the data is the only one with the RSA Private key to decrypt it. My question: Is this the proper way to do something like this? If so, is it safe to send this RSA-Encrypted key with the data since it requires the private key to decrypt? Also - when having the end user generate their Public/Private key pair, what is the best way to save the Private key? I do not want it to be only accessible from one machine, so I am trying to avoid using the user's key store. But MSDN says it is not safe to save the key to a file, so how else can you accomplish this?

    Read the article

  • How do you save and retrieve a Key/IV pair securely?

    - by Shawn Steward
    I'm using VB.Net's RijndaelManaged (RM) to encrypt files, using the RM.GenerateKey and RM.GenerateIV methods to generate the Key and IV and encrypting the file using the CryptoStream class. I'm planning on saving this Key and IV to a file and want to make sure I'm doing it the right way. I am combining the IV+Key, and encrypting that with my RSA Public key and writing it out to a file. Then, to decrypt I use the RSA Private key on this file to get the IV+Key, split them up and set RM.Key and RM.IV to these values and run the decryptor. Is this the best method to accomplish this, or is there a preferred method for saving the IV & Key? Also, what's the best way to construct and deconstruct the byte array? I used the .Concat method to join them together and that seems to work well but I can't seem to find something as easy to deconstruct it. I played with the .Take method that takes the first x # of bytes and it works for the first part but can't find anything that gets the rest of it.

    Read the article

  • C#, AES encryption check!

    - by Data-Base
    I have this code for AES encryption, can some one verify that this code is good and not wrong? it works fine, but I'm more concern about the implementation of the algorithm // Plaintext value to be encrypted. //Passphrase from which a pseudo-random password will be derived. //The derived password will be used to generate the encryption key. //Password can be any string. In this example we assume that this passphrase is an ASCII string. //Salt value used along with passphrase to generate password. //Salt can be any string. In this example we assume that salt is an ASCII string. //HashAlgorithm used to generate password. Allowed values are: "MD5" and "SHA1". //SHA1 hashes are a bit slower, but more secure than MD5 hashes. //PasswordIterations used to generate password. One or two iterations should be enough. //InitialVector (or IV). This value is required to encrypt the first block of plaintext data. //For RijndaelManaged class IV must be exactly 16 ASCII characters long. //KeySize. Allowed values are: 128, 192, and 256. //Longer keys are more secure than shorter keys. //Encrypted value formatted as a base64-encoded string. public static string Encrypt(string PlainText, string Password, string Salt, string HashAlgorithm, int PasswordIterations, string InitialVector, int KeySize) { byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector); byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt); byte[] PlainTextBytes = Encoding.UTF8.GetBytes(PlainText); PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations); byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8); RijndaelManaged SymmetricKey = new RijndaelManaged(); SymmetricKey.Mode = CipherMode.CBC; ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes); MemoryStream MemStream = new MemoryStream(); CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write); CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length); CryptoStream.FlushFinalBlock(); byte[] CipherTextBytes = MemStream.ToArray(); MemStream.Close(); CryptoStream.Close(); return Convert.ToBase64String(CipherTextBytes); } public static string Decrypt(string CipherText, string Password, string Salt, string HashAlgorithm, int PasswordIterations, string InitialVector, int KeySize) { byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector); byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt); byte[] CipherTextBytes = Convert.FromBase64String(CipherText); PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations); byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8); RijndaelManaged SymmetricKey = new RijndaelManaged(); SymmetricKey.Mode = CipherMode.CBC; ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes); MemoryStream MemStream = new MemoryStream(CipherTextBytes); CryptoStream cryptoStream = new CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read); byte[] PlainTextBytes = new byte[CipherTextBytes.Length]; int ByteCount = cryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length); MemStream.Close(); cryptoStream.Close(); return Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount); } Thank you

    Read the article

  • C# Program gets stuck

    - by weirdcsharp
    The program never prints out "test" unless I set a breakpoint on it and step over myself. I don't understand what's happening. Appreciate any help. public partial class Form1 : Form { public Form1() { InitializeComponent(); string testKey = "lkirwf897+22#bbtrm8814z5qq=498j5"; string testIv = "741952hheeyy66#cs!9hjv887mxx7@8y"; string testValue = "random"; string encryptedText = EncryptRJ256(testKey, testIv, testValue); string decryptedText = DecryptRJ256(testKey, testIv, encryptedText); Console.WriteLine("encrypted: " + encryptedText); Console.WriteLine("decrypted: " + decryptedText); Console.WriteLine("test"); } public static string DecryptRJ256(string key, string iv, string text) { string sEncryptedString = text; RijndaelManaged myRijndael = new RijndaelManaged(); myRijndael.Padding = PaddingMode.Zeros; myRijndael.Mode = CipherMode.CBC; myRijndael.KeySize = 256; myRijndael.BlockSize = 256; byte[] keyByte = System.Text.Encoding.ASCII.GetBytes(key); byte[] IVByte = System.Text.Encoding.ASCII.GetBytes(iv); ICryptoTransform decryptor = myRijndael.CreateDecryptor(keyByte, IVByte); byte[] sEncrypted = Convert.FromBase64String(sEncryptedString); byte[] fromEncrypt = new byte[sEncrypted.Length + 1]; MemoryStream msDecrypt = new MemoryStream(sEncrypted); CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read); csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length); return Encoding.ASCII.GetString(fromEncrypt); } public static string EncryptRJ256(string key, string iv, string text) { string sToEncrypt = text; RijndaelManaged myRijndael = new RijndaelManaged(); myRijndael.Padding = PaddingMode.Zeros; myRijndael.Mode = CipherMode.CBC; myRijndael.KeySize = 256; myRijndael.BlockSize = 256; byte[] keyByte = Encoding.ASCII.GetBytes(key); byte[] IVByte = Encoding.ASCII.GetBytes(iv); ICryptoTransform encryptor = myRijndael.CreateEncryptor(keyByte, IVByte); MemoryStream msEncrypt = new MemoryStream(); CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write); byte[] toEncrypt = System.Text.Encoding.ASCII.GetBytes(sToEncrypt); csEncrypt.Write(toEncrypt, 0, toEncrypt.Length); csEncrypt.FlushFinalBlock(); byte[] encrypted = msEncrypt.ToArray(); return Convert.ToBase64String(encrypted); } } edit: Tried Debug.WriteLine Debug.WriteLine("encrypted: " + encryptedText); Debug.WriteLine("decrypted: " + decryptedText); Debug.WriteLine("test"); Output: encrypted: T4hdAcpP5MROmKLeziLvl7couD0o+6EuB/Kx29RPm9w= decrypted: randomtest Not sure why it's not printing the line terminator.

    Read the article

  • add a from to backup routine

    - by Gerard Flynn
    hi how do you put a process bar and button onto this code i have class and want to add a gui on to the code using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; using System.IO; using System.Threading; using Tamir.SharpSsh; using System.Security.Cryptography; using ICSharpCode.SharpZipLib.Checksums; using ICSharpCode.SharpZipLib.Zip; using ICSharpCode.SharpZipLib.GZip; namespace backup { public partial class Form1 : Form { public Form1() { InitializeComponent(); } /// <summary> /// Summary description for Class1. /// </summary> public class Backup { private string dbName; private string dbUsername; private string dbPassword; private static string baseDir; private string backupName; private static bool isBackup; private string keyString; private string ivString; private string[] backupDirs = new string[0]; private string[] excludeDirs = new string[0]; private ZipOutputStream zipOutputStream; private string backupFile; private string zipFile; private string encryptedFile; static void Main() { Backup.Log("BackupUtility loaded"); try { new Backup(); if (!isBackup) MessageBox.Show("Restore complete"); } catch (Exception e) { Backup.Log(e.ToString()); if (!isBackup) MessageBox.Show("Error restoring!\r\n" + e.Message); } } private void LoadAppSettings() { this.backupName = System.Configuration.ConfigurationSettings.AppSettings["BackupName"].ToString(); this.dbName = System.Configuration.ConfigurationSettings.AppSettings["DBName"].ToString(); this.dbUsername = System.Configuration.ConfigurationSettings.AppSettings["DBUsername"].ToString(); this.dbPassword = System.Configuration.ConfigurationSettings.AppSettings["DBPassword"].ToString(); //default to using where we are executing this assembly from Backup.baseDir = System.Reflection.Assembly.GetExecutingAssembly().Location.Substring(0, System.Reflection.Assembly.GetExecutingAssembly().Location.LastIndexOf("\\")) + "\\"; Backup.isBackup = bool.Parse(System.Configuration.ConfigurationSettings.AppSettings["IsBackup"].ToString()); this.keyString = System.Configuration.ConfigurationSettings.AppSettings["KeyString"].ToString(); this.ivString = System.Configuration.ConfigurationSettings.AppSettings["IVString"].ToString(); this.backupDirs = GetSetting("BackupDirs", ','); this.excludeDirs = GetSetting("ExcludeDirs", ','); } private string[] GetSetting(string settingName, char delimiter) { if (System.Configuration.ConfigurationSettings.AppSettings[settingName] != null) { string settingVal = System.Configuration.ConfigurationSettings.AppSettings[settingName].ToString(); if (settingVal.Length > 0) return settingVal.Split(delimiter); } return new string[0]; } public Backup() { this.LoadAppSettings(); if (isBackup) this.DoBackup(); else this.DoRestore(); Log("Finished"); } private void DoRestore() { System.Windows.Forms.OpenFileDialog fileDialog = new System.Windows.Forms.OpenFileDialog(); fileDialog.Title = "Choose .encrypted file"; fileDialog.Filter = "Encrypted files (*.encrypted)|*.encrypted|All files (*.*)|*.*"; fileDialog.InitialDirectory = Backup.baseDir; if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { //string encryptedFile = GetFileName("encrypted"); string encryptedFile = fileDialog.FileName; string decryptedFile = this.GetDecryptedFilename(encryptedFile); //string originalFile = GetFileName("original"); this.Decrypt(encryptedFile, decryptedFile); //this.UnzipFile(decryptedFile, originalFile); } } //use the same filename as the backup except replace ".encrypted" with ".decrypted.zip" private string GetDecryptedFilename(string encryptedFile) { string name = encryptedFile.Substring(0, encryptedFile.LastIndexOf(".")); name += ".decrypted.zip"; return name; } private void DoBackup() { this.backupFile = GetFileName("bak"); this.zipFile = GetFileName("zip"); this.encryptedFile = GetFileName("encrypted"); this.DeleteFiles(); this.zipOutputStream = new ZipOutputStream(File.Create(zipFile)); try { //backup database first if (this.dbName.Length > 0) { this.BackupDB(backupFile); this.ZipFile(backupFile, this.GetName(backupFile)); } //zip any directories specified in config file this.ZipUserSpecifiedFilesAndDirectories(this.backupDirs); } finally { this.zipOutputStream.Finish(); this.zipOutputStream.Close(); } this.Encrypt(zipFile, encryptedFile); this.SCPFile(encryptedFile); this.DeleteFiles(); } /// <summary> /// Deletes any files created by the backup process, namely the DB backup file, /// the zip of all files backuped up, and the encrypred zip file /// </summary> private void DeleteFiles() { File.Delete(this.backupFile); File.Delete(this.zipFile); ///File.Delete(this.encryptedFile); } private void ZipUserSpecifiedFilesAndDirectories(string[] fileNames) { foreach (string fileName in fileNames) { string name = fileName.Trim(); if (name.Length > 0) { Log("Zipping " + name); this.ZipFile(name, this.GetNameFromDir(name)); } } } private void SCPFile(string inputPath) { string sshServer = System.Configuration.ConfigurationSettings.AppSettings["SSHServer"].ToString(); string sshUsername = System.Configuration.ConfigurationSettings.AppSettings["SSHUsername"].ToString(); string sshPassword = System.Configuration.ConfigurationSettings.AppSettings["SSHPassword"].ToString(); if (sshServer.Length > 0 && sshUsername.Length > 0 && sshPassword.Length > 0) { Scp scp = new Scp(sshServer, sshUsername, sshPassword); //Copy a file from local machine to remote SSH server scp.Connect(); Log("Connected to " + sshServer); //scp.Put(inputPath, "/home/wal/temp.txt"); scp.Put(inputPath, GetName(inputPath)); scp.Close(); } else { Log("Not SCP as missing login details"); } } private string GetName(string inputPath) { FileInfo info = new FileInfo(inputPath); return info.Name; } private string GetNameFromDir(string inputPath) { DirectoryInfo info = new DirectoryInfo(inputPath); return info.Name; } private static void Log(string msg) { try { string toLog = DateTime.Now.ToString() + ": " + msg; System.Diagnostics.Debug.WriteLine(toLog); System.IO.FileStream fs = new System.IO.FileStream(baseDir + "app.log", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite); System.IO.StreamWriter m_streamWriter = new System.IO.StreamWriter(fs); m_streamWriter.BaseStream.Seek(0, System.IO.SeekOrigin.End); m_streamWriter.WriteLine(toLog); m_streamWriter.Flush(); m_streamWriter.Close(); fs.Close(); } catch (Exception e) { Console.WriteLine(e.ToString()); } } private byte[] GetFileBytes(string path) { FileStream stream = new FileStream(path, FileMode.Open); byte[] bytes = new byte[stream.Length]; stream.Read(bytes, 0, bytes.Length); stream.Close(); return bytes; } private void WriteFileBytes(byte[] bytes, string path) { FileStream stream = new FileStream(path, FileMode.Create); stream.Write(bytes, 0, bytes.Length); stream.Close(); } private void UnzipFile(string inputPath, string outputPath) { ZipInputStream zis = new ZipInputStream(File.OpenRead(inputPath)); ZipEntry theEntry = zis.GetNextEntry(); FileStream streamWriter = File.Create(outputPath); int size = 2048; byte[] data = new byte[2048]; while (true) { size = zis.Read(data, 0, data.Length); if (size > 0) { streamWriter.Write(data, 0, size); } else { break; } } streamWriter.Close(); zis.Close(); } private bool ExcludeDir(string dirName) { foreach (string excludeDir in this.excludeDirs) { if (dirName == excludeDir) return true; } return false; } private void ZipFile(string inputPath, string zipName) { FileAttributes fa = File.GetAttributes(inputPath); if ((fa & FileAttributes.Directory) != 0) { string dirName = zipName + "/"; ZipEntry entry1 = new ZipEntry(dirName); this.zipOutputStream.PutNextEntry(entry1); string[] subDirs = Directory.GetDirectories(inputPath); //create directories first foreach (string subDir in subDirs) { DirectoryInfo info = new DirectoryInfo(subDir); string name = info.Name; if (this.ExcludeDir(name)) Log("Excluding " + dirName + name); else this.ZipFile(subDir, dirName + name); } //then store files string[] fileNames = Directory.GetFiles(inputPath); foreach (string fileName in fileNames) { FileInfo info = new FileInfo(fileName); string name = info.Name; this.ZipFile(fileName, dirName + name); } } else { Crc32 crc = new Crc32(); this.zipOutputStream.SetLevel(6); // 0 - store only to 9 - means best compression FileStream fs = null; try { fs = File.OpenRead(inputPath); } catch (IOException ioEx) { Log("WARNING! " + ioEx.Message);//might be in use, skip file in this case } if (fs != null) { byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); ZipEntry entry = new ZipEntry(zipName); entry.DateTime = DateTime.Now; // set Size and the crc, because the information // about the size and crc should be stored in the header // if it is not set it is automatically written in the footer. // (in this case size == crc == -1 in the header) // Some ZIP programs have problems with zip files that don't store // the size and crc in the header. entry.Size = fs.Length; fs.Close(); crc.Reset(); crc.Update(buffer); entry.Crc = crc.Value; this.zipOutputStream.PutNextEntry(entry); this.zipOutputStream.Write(buffer, 0, buffer.Length); } } } private void Encrypt(string inputPath, string outputPath) { RijndaelManaged rijndaelManaged = new RijndaelManaged(); byte[] encrypted; byte[] toEncrypt; //Create a new key and initialization vector. //myRijndael.GenerateKey(); //myRijndael.GenerateIV(); /*des.GenerateKey(); des.GenerateIV(); string temp1 = Convert.ToBase64String(des.Key); string temp2 = Convert.ToBase64String(des.IV);*/ //Get the key and IV. byte[] key = Convert.FromBase64String(keyString); byte[] IV = Convert.FromBase64String(ivString); //Get an encryptor. ICryptoTransform encryptor = rijndaelManaged.CreateEncryptor(key, IV); //Encrypt the data. MemoryStream msEncrypt = new MemoryStream(); CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write); //Convert the data to a byte array. toEncrypt = this.GetFileBytes(inputPath); //Write all data to the crypto stream and flush it. csEncrypt.Write(toEncrypt, 0, toEncrypt.Length); csEncrypt.FlushFinalBlock(); //Get encrypted array of bytes. encrypted = msEncrypt.ToArray(); WriteFileBytes(encrypted, outputPath); } private void Decrypt(string inputPath, string outputPath) { RijndaelManaged myRijndael = new RijndaelManaged(); //DES des = new DESCryptoServiceProvider(); byte[] key = Convert.FromBase64String(keyString); byte[] IV = Convert.FromBase64String(ivString); byte[] encrypted = this.GetFileBytes(inputPath); byte[] fromEncrypt; //Get a decryptor that uses the same key and IV as the encryptor. ICryptoTransform decryptor = myRijndael.CreateDecryptor(key, IV); //Now decrypt the previously encrypted message using the decryptor // obtained in the above step. MemoryStream msDecrypt = new MemoryStream(encrypted); CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read); fromEncrypt = new byte[encrypted.Length]; //Read the data out of the crypto stream. int bytesRead = csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length); byte[] readBytes = new byte[bytesRead]; Array.Copy(fromEncrypt, 0, readBytes, 0, bytesRead); this.WriteFileBytes(readBytes, outputPath); } private string GetFileName(string extension) { return baseDir + backupName + "_" + DateTime.Now.ToString("yyyyMMdd") + "." + extension; } private void BackupDB(string backupPath) { string sql = @"DECLARE @Date VARCHAR(300), @Dir VARCHAR(4000) --Get today date SET @Date = CONVERT(VARCHAR, GETDATE(), 112) --Set the directory where the back up file is stored SET @Dir = '"; sql += backupPath; sql += @"' --create a 'device' to write to first EXEC sp_addumpdevice 'disk', 'temp_device', @Dir --now do the backup BACKUP DATABASE " + this.dbName; sql += @" TO temp_device WITH FORMAT --Drop the device EXEC sp_dropdevice 'temp_device' "; //Console.WriteLine("sql="+sql); Backup.Log("Starting backup of " + this.dbName); ExecuteSQL(sql); } /// <summary> /// Executes the specified SQL /// Returns true if no errors were encountered during execution /// </summary> /// <param name="procedureName"></param> private void ExecuteSQL(string sql) { SqlConnection conn = new SqlConnection(this.GetDBConnectString()); try { SqlCommand comm = new SqlCommand(sql, conn); conn.Open(); comm.ExecuteNonQuery(); } finally { conn.Close(); } } private string GetDBConnectString() { StringBuilder builder = new StringBuilder(); builder.Append("Data Source=127.0.0.1; User ID="); builder.Append(this.dbUsername); builder.Append("; Password="); builder.Append(this.dbPassword); builder.Append("; Initial Catalog="); builder.Append(this.dbName); builder.Append(";Connect Timeout=30"); return builder.ToString(); } } } }

    Read the article

  • Encryption using rijndael

    - by user363295
    Hi all. I'm quite new in programming .I wrote the below code in order to prompt the user for a password to encrypting a file, But it just work when the length of password is 8, What can I do on order to accepting any number of characters for the password? string pass = textBox2.Text.ToString(); string password = @"" + pass + ""; UnicodeEncoding UE = new UnicodeEncoding(); byte[] key = UE.GetBytes(password); FileStream fsCrypt = new FileStream(@"c:\\users\\new", FileMode.Create); name = fsCrypt.Name; RijndaelManaged RMCrypto = new RijndaelManaged(); CryptoStream cs = new CryptoStream(fsCrypt, RMCrypto.CreateEncryptor(key, key), CryptoStreamMode.Write); FileStream fsIn = new FileStream(filename, FileMode.Open); int data; while ((data = fsIn.ReadByte()) != -1) cs.WriteByte((byte)data);

    Read the article

  • Converting AES encryption token code in C# to php

    - by joey
    Hello, I have the following .Net code which takes two inputs. 1) A 128 bit base 64 encoded key and 2) the userid. It outputs the AES encrypted token. I need the php equivalent of the same code, but dont know which corresponding php classes are to be used for RNGCryptoServiceProvider,RijndaelManaged,ICryptoTransform,MemoryStream and CryptoStream. Im stuck so any help regarding this would be really appreciated. using System; using System.Text; using System.IO; using System.Security.Cryptography; class AESToken { [STAThread] static int Main(string[] args) { if (args.Length != 2) { Console.WriteLine("Usage: AESToken key userId\n"); Console.WriteLine("key Specifies 128-bit AES key base64 encoded supplied by MediaNet to the partner"); Console.WriteLine("userId specifies the unique id"); return -1; } string key = args[0]; string userId = args[1]; StringBuilder sb = new StringBuilder(); // This example code uses the magic string “CAMB2B”. The implementer // must use the appropriate magic string for the web services API. sb.Append("CAMB2B"); sb.Append(args[1]); // userId sb.Append('|'); // pipe char sb.Append(System.DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ssUTC")); //timestamp Byte[] payload = Encoding.ASCII.GetBytes(sb.ToString()); byte[] salt = new Byte[16]; // 16 bytes of random salt RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); rng.GetBytes(salt); // the plaintext is 16 bytes of salt followed by the payload. byte[] plaintext = new byte[salt.Length + payload.Length]; salt.CopyTo(plaintext, 0); payload.CopyTo(plaintext, salt.Length); // the AES cryptor: 128-bit key, 128-bit block size, CBC mode RijndaelManaged cryptor = new RijndaelManaged(); cryptor.KeySize = 128; cryptor.BlockSize = 128; cryptor.Mode = CipherMode.CBC; cryptor.GenerateIV(); cryptor.Key = Convert.FromBase64String(args[0]); // the key byte[] iv = cryptor.IV; // the IV. // do the encryption ICryptoTransform encryptor = cryptor.CreateEncryptor(cryptor.Key, iv); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write); cs.Write(plaintext, 0, plaintext.Length); cs.FlushFinalBlock(); byte[] ciphertext = ms.ToArray(); ms.Close(); cs.Close(); // build the token byte[] tokenBytes = new byte[iv.Length + ciphertext.Length]; iv.CopyTo(tokenBytes, 0); ciphertext.CopyTo(tokenBytes, iv.Length); string token = Convert.ToBase64String(tokenBytes); Console.WriteLine(token); return 0; } } Please help. Thank You.

    Read the article

  • Oh no! My padding's invalid!

    - by Simon Cooper
    Recently, I've been doing some work involving cryptography, and encountered the standard .NET CryptographicException: 'Padding is invalid and cannot be removed.' Searching on StackOverflow produces 57 questions concerning this exception; it's a very common problem encountered. So I decided to have a closer look. To test this, I created a simple project that decrypts and encrypts a byte array: // create some random data byte[] data = new byte[100]; new Random().NextBytes(data); // use the Rijndael symmetric algorithm RijndaelManaged rij = new RijndaelManaged(); byte[] encrypted; // encrypt the data using a CryptoStream using (var encryptor = rij.CreateEncryptor()) using (MemoryStream encryptedStream = new MemoryStream()) using (CryptoStream crypto = new CryptoStream( encryptedStream, encryptor, CryptoStreamMode.Write)) { crypto.Write(data, 0, data.Length); encrypted = encryptedStream.ToArray(); } byte[] decrypted; // and decrypt it again using (var decryptor = rij.CreateDecryptor()) using (CryptoStream crypto = new CryptoStream( new MemoryStream(encrypted), decryptor, CryptoStreamMode.Read)) { byte[] decrypted = new byte[data.Length]; crypto.Read(decrypted, 0, decrypted.Length); } Sure enough, I got exactly the same CryptographicException when trying to decrypt the data even in this simple example. Well, I'm obviously missing something, if I can't even get this single method right! What does the exception message actually mean? What am I missing? Well, after playing around a bit, I discovered the problem was fixed by changing the encryption step to this: // encrypt the data using a CryptoStream using (var encryptor = rij.CreateEncryptor()) using (MemoryStream encryptedStream = new MemoryStream()) { using (CryptoStream crypto = new CryptoStream( encryptedStream, encryptor, CryptoStreamMode.Write)) { crypto.Write(data, 0, data.Length); } encrypted = encryptedStream.ToArray(); } Aaaah, so that's what the problem was. The CryptoStream wasn't flushing all it's data to the MemoryStream before it was being read, and closing the stream causes it to flush everything to the backing stream. But why does this cause an error in padding? Cryptographic padding All symmetric encryption algorithms (of which Rijndael is one) operates on fixed block sizes. For Rijndael, the default block size is 16 bytes. This means the input needs to be a multiple of 16 bytes long. If it isn't, then the input is padded to 16 bytes using one of the padding modes. This is only done to the final block of data to be encrypted. CryptoStream has a special method to flush this final block of data - FlushFinalBlock. Calling Stream.Flush() does not flush the final block, as you might expect. Only by closing the stream or explicitly calling FlushFinalBlock is the final block, with any padding, encrypted and written to the backing stream. Without this call, the encrypted data is 16 bytes shorter than it should be. If this final block wasn't written, then the decryption gets to the final 16 bytes of the encrypted data and tries to decrypt it as the final block with padding. The end bytes don't match the padding scheme it's been told to use, therefore it throws an exception stating what is wrong - what the decryptor expects to be padding actually isn't, and so can't be removed from the stream. So, as well as closing the stream before reading the result, an alternative fix to my encryption code is the following: // encrypt the data using a CryptoStream using (var encryptor = rij.CreateEncryptor()) using (MemoryStream encryptedStream = new MemoryStream()) using (CryptoStream crypto = new CryptoStream( encryptedStream, encryptor, CryptoStreamMode.Write)) { crypto.Write(data, 0, data.Length); // explicitly flush the final block of data crypto.FlushFinalBlock(); encrypted = encryptedStream.ToArray(); } Conclusion So, if your padding is invalid, make sure that you close or call FlushFinalBlock on any CryptoStream performing encryption before you access the encrypted data. Flush isn't enough. Only then will the final block be present in the encrypted data, allowing it to be decrypted successfully.

    Read the article

  • Encrypting with AES

    - by lolalola
    Why can I encrypt only 16 characters of text? Works: string plainText = "1234567890123456"; Doesn't work: string plainText = "12345678901234561"; Doesn't work: string plainText = "123456789012345"; Code: string plainText = "1234567890123456"; byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText); byte[] keyBytes = System.Text.Encoding.UTF8.GetBytes("1234567890123456"); byte[] initVectorBytes = System.Text.Encoding.UTF8.GetBytes("1234567890123456"); RijndaelManaged symmetricKey = new RijndaelManaged(); symmetricKey.Mode = CipherMode.CBC; symmetricKey.Padding = PaddingMode.Zeros; ICryptoTransform encryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes); MemoryStream memoryStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write); cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length); cryptoStream.FlushFinalBlock(); byte[] cipherTextBytes = memoryStream.ToArray(); memoryStream.Close(); cryptoStream.Close(); string cipherText = Convert.ToBase64String(cipherTextBytes); Console.ReadLine();

    Read the article

  • A Question about .net Rfc2898DeriveBytes class?

    - by IbrarMumtaz
    What is the difference in this class? as posed to just using Encoding.ASCII.GetBytes(string object); I have had relative success with either approach, the former is a more long winded approach where as the latter is simple and to the point. Both seem to allow you to do the same thing eventually but I am struggling to the see the point in using the former over the latter. The basic concept I have been able to grasp is that you can convert string passwords into byte arrays to be used for e.g a symmetric encryption class, AesManaged. Via the RFC class but you get to use SaltValues and password when creating your rfc object. I assume its more secure but still thats an uneducated guess at best ! Also that it allows you to return byte arrays of a certain size, well something like that. heres a few examples to show you where I am coming from? byte[] myPassinBytes = Encoding.ASCII.GetBytes("some password"); or string password = "P@%5w0r]>"; byte[] saltArray = Encoding.ASCII.GetBytes("this is my salt"); Rfc2898DeriveBytes rfcKey = new Rfc2898DeriveBytes(password, saltArray); The 'rfcKey' object can now be used towards setting up the the .Key or .IV properties on a Symmetric Encryption Algorithm class. ie. RijndaelManaged rj = new RijndaelManaged (); rj.Key = rfcKey.Getbytes(rj.KeySize / 8); rj.IV = rfcKey.Getbytes(rj.Blocksize / 8); 'rj' should be ready to go ! The confusing part ... so rather than using the 'rfcKey' object can I not just use my 'myPassInBytes' array to help set-up my 'rj' object???? I have tried doing this in VS2008 and the immediate answer is NO ! but have you guys got a better educated answer as to why the RFC class is used over the other alternative I have mentioned above and why????

    Read the article

  • C#,coding with AES

    - by lolalola
    Hi, why i can coding only 128 bytes text? Work: string plainText = "1234567890123456"; Don't work: string plainText = "12345678901234561"; Don't work: string plainText = "123456789012345"; string plainText = "1234567890123456"; byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText); byte[] keyBytes = System.Text.Encoding.UTF8.GetBytes("1234567890123456"); byte[] initVectorBytes = System.Text.Encoding.UTF8.GetBytes("1234567890123456"); RijndaelManaged symmetricKey = new RijndaelManaged(); symmetricKey.Mode = CipherMode.CBC; symmetricKey.Padding = PaddingMode.Zeros; ICryptoTransform encryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes); MemoryStream memoryStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write); cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length); cryptoStream.FlushFinalBlock(); byte[] cipherTextBytes = memoryStream.ToArray(); memoryStream.Close(); cryptoStream.Close(); string cipherText = Convert.ToBase64String(cipherTextBytes); Console.ReadLine();

    Read the article

  • Invalid character in a Base-64 string when Concatenating and Url encoding a string

    - by Rob
    I’m trying to write some encryption code that is passed through a Url. For the sake of the issue I’ve excluded the actual encryption of the data and just shown the code causing the problem. I take a salt value, convert it to a byte array and then convert that to a base64 string. This string I concatenate to another base64 string (which was previously a byte array). These two base64 strings are then Url encoded. Here’s my code... using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Security.Cryptography; using System.IO; using System.Web; class RHEncryption { private static readonly Encoding ASCII_ENCODING = new System.Text.ASCIIEncoding(); private static readonly string SECRET_KEY = "akey"; private static string md5(string text) { return BitConverter.ToString(new MD5CryptoServiceProvider().ComputeHash(ASCII_ENCODING.GetBytes(text))).Replace("-", "").ToLower(); } public string UrlEncodedData; public RHEncryption() { // encryption object RijndaelManaged aes192 = new RijndaelManaged(); aes192.KeySize = 192; aes192.BlockSize = 192; aes192.Mode = CipherMode.CBC; aes192.Key = ASCII_ENCODING.GetBytes(md5(SECRET_KEY)); aes192.GenerateIV(); // convert Ivector to base64 for sending string base64IV = Convert.ToBase64String(aes192.IV); // salt value string s = "maryhadalittlelamb"; string salt = s.Substring(0, 8); // convert to byte array // and base64 for sending byte[] saltBytes = ASCII_ENCODING.GetBytes(salt.TrimEnd('\0')); string base64Salt = Convert.ToBase64String(saltBytes); //url encode concatenated base64 strings UrlEncodedData = HttpUtility.UrlEncode(base64Salt + base64IV, ASCII_ENCODING); } public string UrlDecodedData() { // decode the url encode string string s = HttpUtility.UrlDecode(UrlEncodedData, ASCII_ENCODING); // convert back from base64 byte[] base64DecodedBytes = null; try { base64DecodedBytes = Convert.FromBase64String(s); } catch (FormatException e) { Console.WriteLine(e.Message.ToString()); Console.ReadLine(); } return s; } } If I then call the UrlDecodedData method I get a “Invalid character in a Base-64 string” exception. This is generated because the base64Salt variable contains an invalid character (I’m guessing a line termination) but I can’t seem to strip it off.

    Read the article

  • AES Encryption. From Python (pyCrypto) to .NET

    - by Why
    I am currently trying to port a legacy Python app over to .NET which contains AES encrpytion using from what I can tell pyCrpyto. I have very limited Python and Crypto experience. The code uses the snippet from the following page. http://www.djangosnippets.org/snippets/1095/ So far I believe I have managed to work out that it that it calls Crypto.Cipher with AES and the first 32 character of our secret key as the password, but no mode or IV. It also puts a prefix on the encrpyed text when it is added to database. What I can't work out is how I can decrypt the existing ecrypted database records in .NET. I have been looking at RijndaelManaged but it requires an IV and can't see any reference to one in python. Can anyone point me in the dirrection to what method could be used in .NET to get the desired result.

    Read the article

  • Securely store a password in program code?

    - by Nick
    My application makes use of the RijndaelManaged class to encrypt data. As a part of this encryption, I use a SecureString object loaded with a password which get's get converted to a byte array and loaded into the RajindaelManaged object's Key at runtime. The question I have is the storage of this SecureString. A user entered password can be entered at run-time, and that can be "securely" loaded into a SecureString object, but if no user entered password is given, then I need to default to something. So ultimately the quesiton comes down to: If I have to have some known string or byte array to load into a SecureString object each time my application runs, how do I do that? The "encrypted" data ultimately gets decrypted by another application, so even if no user entered password is specified, I still need the data to be encrypted while it goes from one app to another. This means I can't have the default password be random, because the other app wouldn't be able to properly decrypt it. One possible solution I'm thinking is to create a dll which only spits out a single passphrase, then I use that passphrase and run it through a couple of different hashing/reorganizing functions at runtime before I ultimately feed it into the secureString object. Would this be secure enough?

    Read the article

  • C++ .NET DLL vs C# Managed Code ? (File Encrypting AES-128+XTS)

    - by Ranhiru
    I need to create a Windows Mobile Application (WinMo 6.x - C#) which is used to encrypt/decrypt files. However it is my duty to write the encryption algorithm which is AES-128 along with XTS as the mode of operation. RijndaelManaged just doesn't cut it :( Very much slower than DES and 3DES CryptoServiceProviders :O I know it all depends on how good I am at writing the algorithm in the most efficient way. (And yes I my self have to write it from scratch but i can take a look @ other implementations) Nevertheless, does writing a C++ .NET DLL to create the encryption/decryption algorithm + all the file handling and using it from C# have a significant performance advantage OVER writing the encryption algorithm + file handling in completely managed C# code? If I use C++ .NET to create the encryption algorithm, should I use MFC Smart Device DLL or ATL? What is the difference and is there any impact on which one I choose? And can i just add a reference to the C++ DLL from C# or should I use P/Invoke? I am fairly competent with C# than C++ but performance plays a major role as I have convinced my lecturers that AES is a very efficient cryptographic algorithm for resource constrained devices. Thanx a bunch :)

    Read the article

1