C# AES-256-CBC 加解密

//C# AES-256-CBC 加解密 
//转载:http://phardera.blogspot.jp/2013/02/c-aes-256-cbc.html

//使用到的名稱空間 : 
using UnityEngine;
using System.Collections;
using System;
using System.Text;
using System.Security.Cryptography;
using System.IO;


//程式碼如下,將字串 "text to be encrypted" 加密後解密看結果是否相同 : 
public class Encrypt : MonoBehaviour 
{
    RijndaelManaged rijalg = new RijndaelManaged();
    
    void Awake()
    {
        //-----------------
        //設定 cipher 格式 AES-256-CBC
        rijalg.BlockSize = 128;
        rijalg.KeySize = 256;
        rijalg.FeedbackSize = 128;
        rijalg.Padding = PaddingMode.PKCS7;
        rijalg.Mode = CipherMode.CBC;

        rijalg.Key = (new SHA256Managed()).ComputeHash(Encoding.ASCII.GetBytes("IHazSekretKey"));
        rijalg.IV = System.Text.Encoding.ASCII.GetBytes("1234567890123456");

        //-----------------
        //加密
        ICryptoTransform encryptor = rijalg.CreateEncryptor(rijalg.Key, rijalg.IV);

        byte[] encrypted;
        using (MemoryStream msEncrypt = new MemoryStream())
        {
            using(CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
            {
                using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                {
                    swEncrypt.Write("text to be enccrypted");
                }
                encrypted = msEncrypt.ToArray();
            }
        }

        //-----------------
        //加密後的 base64 字串 :
        //eiLbdhFSFrDqvUJmjbUgwD8REjBRoRWWwHHImmMLNZA=
        Debug.Log(Convert.ToBase64String(encrypted).ToString());

        //-----------------
        //解密
        ICryptoTransform decryptor = rijalg.CreateDecryptor(rijalg.Key, rijalg.IV);

        string plaintext;
        // Create the streams used for decryption. 
        using (MemoryStream msDecrypt = new MemoryStream(encrypted))
        {
            using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
            {
                using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                {

                    // Read the decrypted bytes from the decrypting stream 
                    // and place them in a string.
                    plaintext = srDecrypt.ReadToEnd();
                }
            }
        }

        //-----------------
        //最後印出字串 "text to be encrypted"
        Debug.Log(plaintext);
    }
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C# 和 Java 都支持 AES 加密算法,因此可以在两种语言中进行加密解密。下面是一个示例代码,演示了 C# 和 Java 中如何使用 AES 加密解密数据。 首先是 Java 中的代码,用于加密数据: ```java import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.util.Base64; public class AesEncryption { private static final String ALGORITHM = "AES/CBC/PKCS5Padding"; private static final String KEY = "0123456789abcdef"; // 16-byte key private static final String IV = "0123456789abcdef"; // 16-byte initialization vector public static String encrypt(String data) throws Exception { Cipher cipher = Cipher.getInstance(ALGORITHM); SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(), "AES"); IvParameterSpec ivSpec = new IvParameterSpec(IV.getBytes()); cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec); byte[] encrypted = cipher.doFinal(data.getBytes()); return Base64.getEncoder().encodeToString(encrypted); } } ``` 这个代码使用了 AES/CBC/PKCS5Padding 加密算法,采用了 16 字节的密钥和初始化向量。`encrypt()` 方法接受一个字符串参数,并返回加密后的字符串。 接下来是 C# 中的代码,用于解密数据: ```csharp using System; using System.Security.Cryptography; using System.Text; public class AesDecryption { private static readonly byte[] Key = Encoding.UTF8.GetBytes("0123456789abcdef"); // 16-byte key private static readonly byte[] Iv = Encoding.UTF8.GetBytes("0123456789abcdef"); // 16-byte initialization vector public static string Decrypt(string data) { byte[] encryptedData = Convert.FromBase64String(data); using (Aes aes = Aes.Create()) { aes.Key = Key; aes.IV = Iv; aes.Padding = PaddingMode.PKCS7; aes.Mode = CipherMode.CBC; ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV); byte[] decrypted = decryptor.TransformFinalBlock(encryptedData, 0, encryptedData.Length); return Encoding.UTF8.GetString(decrypted); } } } ``` 这个代码使用了相同的 AES/CBC/PKCS5Padding 加密算法和 16 字节的密钥和初始化向量。`Decrypt()` 方法接受一个加密的字符串参数,并返回解密后的字符串。 使用这两个类,可以在 C# 和 Java 中进行 AES 加密解密操作。注意,密钥和初始化向量需要在两种语言中保持一致。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值