找回密码
 立即注册
注册 登录
×
热搜: 活动 交友 discuz
查看: 96|回复: 1

C#与javascript通用AES加密解密

[复制链接]

1

主题

2

帖子

4

积分

新手上路

Rank: 1

积分
4
发表于 2023-1-12 07:36:40 | 显示全部楼层 |阅读模式
c#版
/// <summary>  
/// AES加密  
/// </summary>  
/// <param name="input">明文</param>  
/// <param name="key">密钥</param>  
/// <returns></returns>  
public string AESEncrypt(string input, string key)
{
    byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);
    byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(input);

    RijndaelManaged rDel = new RijndaelManaged();
    rDel.Key = keyArray;
    rDel.IV = keyArray;
    rDel.Mode = CipherMode.CBC;
    rDel.Padding = PaddingMode.PKCS7;
    ICryptoTransform cTransform = rDel.CreateEncryptor();
    byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

    return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}

/// <summary>  
/// AES解密  
/// </summary>  
/// <param name="input">密文</param>  
/// <param name="key">密钥</param>  
/// <returns></returns>  
public string AESDecrypt(string input, string key)
{
    byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);
    byte[] toEncryptArray = Convert.FromBase64String(input);

    RijndaelManaged rDel = new RijndaelManaged();
    rDel.Key = keyArray;
    rDel.IV = keyArray;
    rDel.Mode = CipherMode.CBC;
    rDel.Padding = PaddingMode.PKCS7;
    ICryptoTransform cTransform = rDel.CreateDecryptor();
    byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

    return UTF8Encoding.UTF8.GetString(resultArray);
}

nodejs-javascript版
  public static aesEncrypt(input: string, key: string): string {
    var iv = key;
    var cipher = crypto.createCipheriv('aes-128-cbc', key, iv);
    var crypted = cipher.update(input, 'utf8', 'binary');
    crypted += cipher.final('binary');
    crypted = Buffer.from(crypted, 'binary').toString('base64');

    return crypted;
  }

  public static aesDecrypt(input: string, key: string): string {
    var iv = key;
    var decode = Buffer.from(input, "base64").toString("binary")
    var cipher = crypto.createDecipheriv('aes-128-cbc', key, iv);
    var decrypted = cipher.update(decode, 'binary', 'utf8');
    decrypted += cipher.final('utf8');

    return decrypted;
  }

key 可以参考设置为:sfe023f_9fd&fwfl

参考来源:https://github.com/fan4428/aes-128-cbc
回复

使用道具 举报

1

主题

8

帖子

14

积分

新手上路

Rank: 1

积分
14
发表于 2025-2-28 17:42:46 | 显示全部楼层
为保住菊花,这个一定得回复!
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋| 黑客通

GMT+8, 2025-4-6 21:53 , Processed in 0.123855 second(s), 23 queries .

Powered by Discuz! X3.4

Copyright © 2020, LianLian.

快速回复 返回顶部 返回列表