使用AES 256 C#php加密和解密非常长的字符串

时间:2014-01-28 14:32:15

标签: c# php encryption cryptography aes

我有一个用PHP编写的加密函数来加密我的数据,还有一个C#中的解密函数解密它并在屏幕上打印(我在Unity引擎中开发游戏)。所以问题是,如果数据字符串很长,它将不会解密它的最后一部分......我正在使用AES 256加密密钥

php函数:

$username = "Name"
$id = 1;
$email = "email@example.com"

$data = $username . "\n" . $id . "\n" . $email;

$key = "my 256 bit key"; //32 bytes
function aes256Encrypt($key, $data) {
    if(32 !== strlen($key)) $key = hash('SHA256', $key, true);
    $padding = 16 - (strlen($data) % 16);
    $data .= str_repeat(chr($padding), $padding);
    return mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, str_repeat("\0", 16));
}

echo base64_encode(aes256Encrypt($key, $data));

这是我的C#完整代码,它在游戏屏幕上打印解密的字符串:

using UnityEngine;
using System.Collections;
using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;

public class session : MonoBehaviour {

    private string sessionURL = "http://localhost/xampp/game/session.php";

    void Start () 
    {
        StartCoroutine(GetSession());
    }

    IEnumerator GetSession()
    {
        gameObject.guiText.text = "Loading Session";
        WWW ses_get = new WWW(sessionURL);
        yield return ses_get;

        string key = "my 256 bit key";
        string base64_ciphered_text = ses_get.text;
        String sestext = Decrypt(base64_ciphered_text, key);

        if (ses_get.error != null)
        {
            print("There was an error getting the session: " + ses_get.error);
        }
        else
        {
            guiText.richText = true;
            guiText.text = sestext;
        }
    }


    public String Decrypt(String text, String key)
    {
        //decode cipher text from base64
        byte[] cipher = Convert.FromBase64String(text);
        //get key bytes
        byte[] btkey = Encoding.ASCII.GetBytes(key);

        //init AES 256
        RijndaelManaged aes256 = new RijndaelManaged();
        aes256.Mode = CipherMode.ECB;
        aes256.Padding = PaddingMode.Zeros;

        //decrypt
        ICryptoTransform decryptor = aes256.CreateDecryptor(btkey, null);
        MemoryStream ms = new MemoryStream(cipher);
        CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read);

        byte[] plain = new byte[cipher.Length];
        int decryptcount = cs.Read(plain, 0, plain.Length);

        ms.Close();
        cs.Close();

        //return plaintext in String
        return Encoding.UTF8.GetString(plain, 0, decryptcount);
    }

}

有人有个主意吗?

我的意思的一个例子: $ data:http://puu.sh/6BkU4.png 屏幕输出:http://puu.sh/6BkTF.jpg

1 个答案:

答案 0 :(得分:0)

你在PHP中使用CBC模式,在C#中使用ECB,所以在第一个块之后就会出错。在这两种情况下都需要使用相同的模式。