Java、C#双语版配套AES加解密示例

  这年头找个正经能用的东西那是真难,网上一搜索一大堆,正经能用的没几个,得,最后还是得靠自己,正巧遇上需要AES加解密的地方了,而且还是Java和C#间的相互加解密操作,这里做个备忘

  这里采用的加解密使用base64转码方法,ECB模式,PKCS5Padding填充,密码必须是16位,否则会报错哈

  模式:Java的ECB对应C#的System.Security.Cryptography.CipherMode.ECB

  填充方法:Java的PKCS5Padding对应C#System.Security.Cryptography.PaddingMode.PKCS7

  Java和C#版的加解密是互通的,也就是能相互加解密,编码明确指定了采用UTF-8,有需要其他编码方法的请自行扩展

Java版

package nb.tmall.util;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.*;

@SuppressWarnings("restriction")
public class EncryptUtil {

    public static String aesEncrypt(String str, String key) throws Exception {
        if (str == null || key == null) return null;
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes("utf-8"), "AES"));
        byte[] bytes = cipher.doFinal(str.getBytes("utf-8"));
        return new BASE64Encoder().encode(bytes);
    }

    public static String aesDecrypt(String str, String key) throws Exception {
        if (str == null || key == null) return null;
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes("utf-8"), "AES"));
        byte[] bytes = new BASE64Decoder().decodeBuffer(str);
        bytes = cipher.doFinal(bytes);
        return new String(bytes, "utf-8");
    }
}

C#版

using System;
using System.Security.Cryptography;
using System.Text;

namespace CSharp.Util.Security
{

        /// <summary>
        ///  AES 加密
        /// </summary>
        /// <param name="str"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string AesEncrypt(string str, string key)
        {
            if (string.IsNullOrEmpty(str)) return null;
            Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str);

            System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
            {
                Key = Encoding.UTF8.GetBytes(key),
                Mode = System.Security.Cryptography.CipherMode.ECB,
                Padding = System.Security.Cryptography.PaddingMode.PKCS7
            };

            System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateEncryptor();
            Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

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

        /// <summary>
        ///  AES 解密
        /// </summary>
        /// <param name="str"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string AesDecrypt(string str, string key)
        {
            if (string.IsNullOrEmpty(str)) return null;
            Byte[] toEncryptArray = Convert.FromBase64String(str);

            System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
            {
                Key = Encoding.UTF8.GetBytes(key),
                Mode = System.Security.Cryptography.CipherMode.ECB,
                Padding = System.Security.Cryptography.PaddingMode.PKCS7
            };

            System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateDecryptor();
            Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            return Encoding.UTF8.GetString(resultArray);
        }
    }
}
时间: 2024-10-14 10:53:37

Java、C#双语版配套AES加解密示例的相关文章

C#与java中的AES加解密互解算法

一.C#版AES加解密算法 public class AESCode { public string Key { get; set; } public string Encrypt(string val) { if (string.IsNullOrEmpty(val)) return null; #if CSP using (AesCryptoServiceProvider des = new AesCryptoServiceProvider()) #else using (AesManaged

aes加解密 Illegal key size

做aes加密时,发生一个奇怪的错误,在本地环境是好的,发布到测试环境就出问题, java.security.InvalidKeyException: Illegal key size 想到本地环境之前也是遇到加密问题,从oracle官网下载了两个文件,覆盖本地文件得到解决. 推测测试环境肯定也是此原因,照此方法,测试环境aes加解密问题得到解决,特此记录下来,避免下次再踩坑. 问题背景: Java几乎各种常用加密算法都能找到对应的实现.因为美国的出口限制,Sun通过权限文件(local_poli

[掌眼]iOS / Android / java / node.js 通用的 AES256 加解密算法

example.m NSString *text = @"text"; NSString *key32 = @"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding]; NSString *encryptedData = [[data AES256EncryptWithKey:key32] base64EncodedStringWi

Android jni aes加解密,实现文件的加解密,具体实现可以自行修改,上面的代码为简单介绍,下面的是JNI端实现文件加解密,可以修改为字符串加解密

#include "aes.h" #include "modes.h" #include "e_os2.h" #include "aes_locl.h" #include "opensslconf.h" AES_KEY aes; //aes cbc模式加解密用到的向量 unsigned char iv[AES_BLOCK_SIZE]; for (i = 0; i < AES_BLOCK_SIZE; i

aes加解密前后端-后台

一.web.xml: <filter> <filter-name>fastLoginFilter</filter-name> <filter-class>com.shencai.xf.common.util.FastLoginFilter</filter-class> </filter> <filter-mapping> <filter-name>fastLoginFilter</filter-name&

AES加解密算法Qt实现

[声明] (1) 本文源码 在一位未署名网友源码基础上,利用Qt编程,实现了AES加解密算法,并添加了文件加解密功能.在此表示感谢!该源码仅供学习交流,请勿用于商业目的. (2) 图片及描述 除图1外,图片及部分解析来自http://zh.wikipedia.org/wiki/%E9%AB%98%E7%BA%A7%E5%8A%A0%E5%AF%86%E6%A0%87%E5%87%86.图1为个人劳动成果,请勿盗用此图. [简介] AES(Advanced Encryption Standard,

java 使用pem密钥进行RSA加解密

1.使用openssl生成私钥和公钥 openssl下载地址:http://www.openssl.org/source openssl生成私钥命令:  genrsa -out rsa_private_key.pem 1024 openssl生成公钥命令:  rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem 2.此时在openssl安装目录下的bin文件夹可以看到 rsa_private_key.pem 和 rsa_publi

Java中的AES加解密

直接上代码,Base64使用的是Java8的方法,如没有,替换即可 KEY:即密码 IV:即偏移量,可自订,十六位 加密方式:AES/CBC/PKCS5Padding,128位加密 如果想用256位和PKCS7Padding需要额外导入包 import javax.crypto.*; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.security.Inva

Nodejs与Java通用AES加解密

一.nodejs加解密工具类: /** * AES util */ const CryptoJS = require('crypto-js') export const AES = { //加密 encode: (params) => { let { data, param, key } = params let result = JSON.parse(JSON.stringify(data)) param.forEach(ele => { let data = result[ele] key