Quantcast
Channel: Security
Viewing all articles
Browse latest Browse all 4737

Encrypt and Decrypt in C# Web Pages

$
0
0

Hi All,

I found the below code for encryption and decryption of password, but unfortunately it is not working. I googled through so many sites, almost everyone tells, they are able to work with it, but it is not working for me. Can someone please help. It is really very urgent. The code is basically failing at:

using

(Stream stream = newCryptoStream(memory, transform, CryptoStreamMode

.Write))

{
stream.Write(data, 0, data.Length);
}

Error Description:

System.Security.Cryptography.CryptographicException: Length of the data to decrypt is invalid.

staticpublicclass

Crypto

{

privatestaticreadonlybyte[] salt = Encoding.ASCII.GetBytes("Ent3r your oWn S@lt v@lu# h#r3"

);

publicstaticstring Encrypt(string textToEncrypt, string

encryptionPassword)

{

encryptionPassword =

test@123

;

var

algorithm = GetAlgorithm(encryptionPassword);

byte

[] encryptedBytes;

using (ICryptoTransform

encryptor = algorithm.CreateEncryptor(algorithm.Key, algorithm.IV))

{

byte[] bytesToEncrypt = Encoding

.UTF8.GetBytes(textToEncrypt);

encryptedBytes = InMemoryCrypt(bytesToEncrypt, encryptor);

}

returnConvert

.ToBase64String(encryptedBytes);

}

publicstaticstring Decrypt(string encryptedText, string

encryptionPassword)

{

var

algorithm = GetAlgorithm(encryptionPassword);

byte

[] descryptedBytes;

using (ICryptoTransform

decryptor = algorithm.CreateDecryptor(algorithm.Key, algorithm.IV))

{

byte[] encryptedBytes = Convert

.FromBase64String(encryptedText);

descryptedBytes = InMemoryCrypt(encryptedBytes, decryptor);

}

returnEncoding

.UTF8.GetString(descryptedBytes);

}

// Performs an in-memory encrypt/decrypt transformation on a byte array.

privatestaticbyte[] InMemoryCrypt(byte[] data, ICryptoTransform

transform)

{

MemoryStream memory = newMemoryStream

();

using (Stream stream = newCryptoStream(memory, transform, CryptoStreamMode

.Write))

{

stream.Write(data, 0, data.Length);

}

return

memory.ToArray();

}

// Defines a RijndaelManaged algorithm and sets its key and Initialization Vector (IV)

// values based on the encryptionPassword received.

privatestaticRijndaelManaged GetAlgorithm(string

encryptionPassword)

{

// Create an encryption key from the encryptionPassword and salt.

var key = newRfc2898DeriveBytes

(encryptionPassword, salt);

// Declare that we are going to use the Rijndael algorithm with the key that we've just got.

var algorithm = newRijndaelManaged

();

int

bytesForKey = algorithm.KeySize / 8;

int

bytesForIV = algorithm.BlockSize / 8;

algorithm.Key = key.GetBytes(bytesForKey);

algorithm.IV = key.GetBytes(bytesForIV);

return

algorithm;

}

}


Viewing all articles
Browse latest Browse all 4737

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>