Aes 加密简单例子

必须引入: using System.Security.Cryptography;

AES 算法基于排列和置换运算。排列是对数据重新进行安排,置换是将一个数据单元替换为另一个。AES 使用几种不同的方法来执行排列和置换运算。

AES 是一个迭代的、对称密钥分组的密码,它可以使用128、192 和 256 位密钥,并且用 128 位(16字节)分组加密和解密数据。与公共密钥密码使用密钥对不同,对称密钥密码使用相同的密钥加密和解密数据。通过分组密码返回的加密数据的位数与输入数据相同。迭代加密使用一个循环结构,在该循环中重复置换和替换输入数据。

 

下面直接进入代码中(解密同理为你过程,但请注意因为aes是块加密,所以在解密出块前要把最后的\0清除,可以记录加密时的长度来解密)

ContractedBlock.gif ExpandedBlockStart.gif 加密部分
protected void btEncrypt_Click(object sender, EventArgs e)
ExpandedBlockStart.gifContractedBlock.gif    
{
        
if (!string.IsNullOrEmpty(txtInput.Text))
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            txtInputLength.Text 
= string.Empty;
            AesManaged aesm 
= new AesManaged();
            txtKey.Text 
= string.Empty;
            
foreach (byte b in aesm.Key)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                txtKey.Text 
+= string.Format("{0}\t", b.ToString());
            }

            txtKey.Text 
+= string.Format("Length:{0}", aesm.Key.Length);

            txtVI.Text 
= string.Empty;
            
foreach (byte b in aesm.IV)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                txtVI.Text 
+= string.Format("{0}\t", b.ToString());
            }

            txtVI.Text 
+= string.Format("Length:{0}", aesm.IV.Length);

            
byte[] plainTextBytes = Encoding.Unicode.GetBytes(txtInput.Text);
            txtInputLength.Text 
= plainTextBytes.Length.ToString();
            
byte[] encyptedBytes;
            encyptedBytes 
= aesm.CreateEncryptor().TransformFinalBlock(plainTextBytes, 0, plainTextBytes.Length);
            txtEncrypted.Text 
= string.Empty;
            
foreach (byte b in encyptedBytes)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                txtEncrypted.Text 
+= string.Format("{0}\t", b.ToString());
            }

            txtEncrypted.Text 
+= string.Format("Length:{0}", encyptedBytes.Length);
        }

    }

 

ContractedBlock.gif ExpandedBlockStart.gif 解密部分
encyptedBytes = aesm.CreateDecryptor().TransformFinalBlock(encyptedBytes, 0, encyptedBytes .Length);
            Array.Copy(encyptedBytes, 
0, plainTextBytes, 0, plainTextBytes.Length);
            Response.Write(Encoding.Unicode.GetString(plainTextBytes));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值