CSharpTest.Net
Encrypt(String) Method
See Also  Example Send Feedback Download Help File
CSharpTest.Net.Library Assembly > CSharpTest.Net.Crypto Namespace > CryptoKey Class > Encrypt Method : Encrypt(String) Method

text

Glossary Item Box

Encrypts the encoded text and returns the base-64 encoded result

Syntax

Visual Basic (Declaration) 
Public Overloads Function Encrypt( _
   ByVal text As String _
) As String
C# 
public string Encrypt( 
   string text
)

Parameters

text

Example

Library/Library.Test/TestEncryption.cs

C#Copy Code
byte[] ivrandom = new byte[16];
new Random().NextBytes(ivrandom);

using (AESCryptoKey k1 = new AESCryptoKey())
using (AESCryptoKey k2 = new AESCryptoKey(k1.Key, k1.IV))
using (AESCryptoKey kBadIv = new AESCryptoKey(k1.Key, ivrandom))
{
    Assert.AreEqual(k1.Key, k2.Key);
    Assert.AreEqual(k1.IV, k2.IV);
    Assert.AreEqual("test", k2.Decrypt(k1.Encrypt("test")));

    Assert.AreEqual(k1.Key, kBadIv.Key);
    Assert.AreNotEqual(k1.IV, kBadIv.IV);
    try
    {   //one of two possible outcomes, junk or exception
        Assert.AreNotEqual("test", kBadIv.Decrypt(k1.Encrypt("test")));
    }
    catch (System.Security.Cryptography.CryptographicException) { }
}
VB.NETCopy Code
Dim ivrandom As Byte() = New Byte(16) {}
New Random().NextBytes(ivrandom)

Using k1 As New AESCryptoKey()
    Using k2 As New AESCryptoKey(k1.Key, k1.IV)
        Using kBadIv As New AESCryptoKey(k1.Key, ivrandom)
            Assert.AreEqual(k1.Key, k2.Key)
            Assert.AreEqual(k1.IV, k2.IV)
            Assert.AreEqual("test", k2.Decrypt(k1.Encrypt("test")))

            Assert.AreEqual(k1.Key, kBadIv.Key)
            Assert.AreNotEqual(k1.IV, kBadIv.IV)
            Try
                'one of two possible outcomes, junk or exception
                Assert.AreNotEqual("test", kBadIv.Decrypt(k1.Encrypt("test")))
            Catch generatedExceptionName As System.Security.Cryptography.CryptographicException
            End Try
        End Using
    End Using
End Using

Requirements

Target Platforms: Windows XP, Windows Server 2003, Windows Vista, Windows Server 2008, Windows 7

See Also

Generated with Document! X 2011 by Innovasys