开发者

Implementing PHP AES Function in .NET (C#)

I have given a task in which I need to encrypt an user's ID using AES encryption, what they want is I need to pass in a parameter in a website just like this.

URL : http://www.site.com/event/sample.jce Parameter : ?param= encrypted text

aside from that there was an attched php sample that they want me to follow to encrypt but I don't have an idea on how to convert this one in .NET

function getEncrypt($sStr, $sKey, $sIV){ $sCipher = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $sKey, $sStr, MCRYPT开发者_如何学编程_MODE_CFB, $sIV); return bin2hex($sCipher); }

$sStr = "13410##13";

$sKey = "mediaservice1234"; $sKey = "kjcemsdev3jangho"; // Do not change

$sIV = "fs0tjwkdgh0akstp"; // Do not change

$tmp= getEncrypt($sStr, $sKey, $sIV);

Could somebody help me to understand this codes? or better if they could help me to convert this one on .NEt code? Thanks. :)


Try this, you need to set the FeedbackSize and Padding:

public static string Encrypt(string plaintext)
        {
            RijndaelManaged rijndaelCipher = new RijndaelManaged();
            //RijndaelManaged rijndaelCipher = new RijndaelManaged();
            rijndaelCipher.FeedbackSize = 8;
            rijndaelCipher.Mode = CipherMode.CFB;
            rijndaelCipher.KeySize = 128;
           // rijndaelCipher.BlockSize = 128;
            rijndaelCipher.BlockSize = 128;
            rijndaelCipher.Padding = PaddingMode.Zeros;
            byte[] plaintextByte = System.Text.Encoding.ASCII.GetBytes(plaintext);
            //Rfc2898DeriveBytes
            ASCIIEncoding textConverter = new ASCIIEncoding();
            rijndaelCipher.Key = textConverter.GetBytes(PRIVATEKEY); ;
            rijndaelCipher.IV = Convert.FromBase64String(PRIVATEIV);


            ICryptoTransform encryptor = rijndaelCipher.CreateEncryptor();

            //http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged(VS.80).aspx
            //Encrypt the data.
            MemoryStream msEncrypt = new MemoryStream();
            CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);

            //Convert the data to a byte array.
            byte[] toEncrypt = textConverter.GetBytes(plaintext);


            //Write all data to the crypto stream and flush it.
            csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);
            csEncrypt.FlushFinalBlock();
            byte[] encrypted = new byte[16];
            //Get encrypted array of bytes.
            encrypted = msEncrypt.ToArray();


            return Convert.ToBase64String(encrypted);
        }


Here you can find some more information about using the AES encryption in .net:

http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged%28VS.80%29.aspx

The code is pretty straight forward.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜