The example shown on the video is played against the video.CodeThe test failed. After I searched the internet, I changed the test to succeeded. I don't know why the test was correct on the same code video as the video and my test failed, write it down for later use!
Code
/// <Summary> String encryption and decryption
///
/// </Summary>
Public Class Encrypt
{
Private Symmetricalgorithm MCSP;
Private Const String Civ = " OO */^ FSa " ; // Key, which can only be 8 bits
Private Const String Ckey = " F123 $ dew " ; // Initialization vector, which can only be 8 bits
Public Encrypt ()
{
MCSP = New Descryptoserviceprovider ();
}
/// <Summary> Encrypted string
///
/// </Summary>
/// <Param name = "value"> </param>
/// <Returns> </returns>
Public String Encryptstring ( String Value)
{
Icryptotransform CT;
Memorystream MS;
Cryptostream Cs;
Byte [] BYT;
// Convert. frombase64string (ckey/CIV) is used in the video. However, if I use convert, errors always occur. What is wrong?
CT = MCSP. createencryptor (encoding. ASCII. getbytes (ckey), encoding. ASCII. getbytes (CIV ));
Byt = Encoding. utf8.getbytes (value );
MS = New Memorystream ();
CS = New Cryptostream (MS, CT, cryptostreammode. Write );
CS. Write (BYT, 0 , Byt. Length );
CS. flushfinalblock ();
CS. Close ();
Return Convert. tobase64string (Ms. toarray ());
}
/// <Summary> Decrypt string
///
/// </Summary>
/// <Param name = "value"> </param>
/// <Returns> </returns>
Public String Decryptstring ( String Value)
{
Icryptotransform CT;
Memorystream MS;
Cryptostream Cs;
Byte [] BYT;
CT = MCSP. createdecryptor (encoding. ASCII. getbytes (ckey), encoding. ASCII. getbytes (CIV ));
Byt = Convert. frombase64string (value );
MS = New memorystream ();
CS = New cryptostream (MS, CT, cryptostreammode. write);
CS. write (BYT, 0 , byt. length);
CS. flushfinalblock ();
CS. close ();
ReturnEncoding. utf8.getstring (Ms. toarray ());
}
}
Test code:
Static Void Main ( String [] ARGs)
{
Console. Write ( " Enter the string to be encrypted: " );
String Str = Console. Readline ();
Console. writeline ( " After encryption: " + New Encrypt (). encryptstring (STR ));
Console. Readline ();
Console. Write ( " Enter the string to decrypt: " );
String Str2 = Console. Readline ();
Console. writeline ( " After decryption: " + New Encrypt (). decryptstring (str2 ));
Console. Readline ();
}
Test results: