.NET/android/java/iOS AES通用加密解密(修正安卓)

时间:2023-12-06 10:14:26

移动端越来越火了,我们在开发过程中,总会碰到要和移动端打交道的场景,比如.NET和android或者iOS的打交道。为了让数据交互更安全,我们需要对数据进行加密传输。今天研究了一下,把几种语言的加密都实践了一遍,实现了.NET,java(android),iOS都同一套的加密算法,下面就分享给大家。(转载自:http://www.cnblogs.com/jys509/p/4768120.html 有对安卓的代码单独贴出。)

AES加密有多种算法模式,下面提供两套模式的可用源码。

加密方式:

  1. 先将文本AES加密
  2. 返回Base64转码

解密方式:

  1. 将数据进行Base64解码
  2. 进行AES解密

一、CBC(Cipher Block Chaining,加密块链)模式

是一种循环模式,前一个分组的密文和当前分组的明文异或操作后再加密,这样做的目的是增强破解难度.

  • 密钥
  • 密钥偏移量

java加密AESOperator类:

 package com.bci.wx.base.util;

 import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec; 7 import sun.misc.BASE64Decoder;
8 import sun.misc.BASE64Encoder; /**
* AES 是一种可逆加密算法,对用户的敏感信息加密处理 对原始数据进行AES加密后,在进行Base64编码转化;
*/
public class AESOperator { /*
* 加密用的Key 可以用26个字母和数字组成 此处使用AES-128-CBC加密模式,key需要为16位。
*/
private String sKey = "smkldospdosldaaa";//key,可自行修改
private String ivParameter = "0392039203920300";//偏移量,可自行修改
private static AESOperator instance = null; private AESOperator() { } public static AESOperator getInstance() {
if (instance == null)
instance = new AESOperator();
return instance;
} public static String Encrypt(String encData ,String secretKey,String vector) throws Exception { if(secretKey == null) {
return null;
}
if(secretKey.length() != 16) {
return null;
}
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] raw = secretKey.getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
IvParameterSpec iv = new IvParameterSpec(vector.getBytes());// 使用CBC模式,需要一个向量iv,可增加加密算法的强度
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(encData.getBytes("utf-8"));
47 return new BASE64Encoder().encode(encrypted);// 此处使用BASE64做转码。
} // 加密
public String encrypt(String sSrc) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] raw = sKey.getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());// 使用CBC模式,需要一个向量iv,可增加加密算法的强度
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
59 return new BASE64Encoder().encode(encrypted);// 此处使用BASE64做转码。
} // 解密
public String decrypt(String sSrc) throws Exception {
try {
byte[] raw = sKey.getBytes("ASCII");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);// 先用base64解密
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original, "utf-8");
return originalString;
} catch (Exception ex) {
return null;
}
} public String decrypt(String sSrc,String key,String ivs) throws Exception {
try {
byte[] raw = key.getBytes("ASCII");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec(ivs.getBytes());
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);// 先用base64解密
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original, "utf-8");
return originalString;
} catch (Exception ex) {
return null;
}
} public static String encodeBytes(byte[] bytes) {
StringBuffer strBuf = new StringBuffer(); for (int i = 0; i < bytes.length; i++) {
strBuf.append((char) (((bytes[i] >> 4) & 0xF) + ((int) 'a')));
strBuf.append((char) (((bytes[i]) & 0xF) + ((int) 'a')));
} return strBuf.toString();
} public static void main(String[] args) throws Exception {
// 需要加密的字串
String cSrc = "[{\"request_no\":\"1001\",\"service_code\":\"FS0001\",\"contract_id\":\"100002\",\"order_id\":\"0\",\"phone_id\":\"13913996922\",\"plat_offer_id\":\"100094\",\"channel_id\":\"1\",\"activity_id\":\"100045\"}]"; // 加密
long lStart = System.currentTimeMillis();
String enString = AESOperator.getInstance().encrypt(cSrc);
System.out.println("加密后的字串是:" + enString); long lUseTime = System.currentTimeMillis() - lStart;
System.out.println("加密耗时:" + lUseTime + "毫秒");
// 解密
lStart = System.currentTimeMillis();
String DeString = AESOperator.getInstance().decrypt(enString);
System.out.println("解密后的字串是:" + DeString);
lUseTime = System.currentTimeMillis() - lStart;
System.out.println("解密耗时:" + lUseTime + "毫秒");
} }

Android加密AESOperator类:(以下红色部分是JAVA和安卓代码不同的地方,安卓代码里面和IOS,c#结果一样的加密/解密方法是Encrypt64/Decrypt64)

 package com.example.demo2;

 import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec; 7 import android.util.Base64; public class AESEncrypto {
public static byte[] _key = { 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97,
98, 99, 100, 101, 102 };// 初始化矩阵
public static String ivParameter="0392039203920300";
// 加密
public static String Encrypt64(String sSrc, String sKey) throws Exception {
if (sKey == null) {
System.out.print("Key为空null");
return null;
}
// 判断Key是否为16位
if (sKey.length() != 16) {
System.out.print("Key长度不是16位");
return null;
}
byte[] raw = sKey.getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");// "算法/模式/补码方式"
IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());// 使用CBC模式,需要一个向量iv,可增加加密算法的强度
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(sSrc.getBytes()); 31 return Base64.encodeToString(encrypted, 0);// 此处使用BASE64做转码功能,同时能起到2次加密的作用。
} // 解密
public static String Decrypt64(String sSrc, String sKey) throws Exception {
try {
// 判断Key是否正确
if (sKey == null) {
System.out.print("Key为空null");
return null;
}
// 判断Key是否为16位
if (sKey.length() != 16) {
System.out.print("Key长度不是16位");
return null;
}
byte[] raw = sKey.getBytes("ASCII");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec(
ivParameter.getBytes());
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
53 byte[] encrypted1 = Base64.decode(sSrc, 0);// 先用base64解密
try {
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original);
return originalString;
} catch (Exception e) {
System.out.println(e.toString());
return null;
}
} catch (Exception ex) {
System.out.println(ex.toString());
return null;
}
} public static String Encrypt(String sSrc, String sKey) throws Exception {
if (sKey == null) {
System.out.print("Key为空null");
return null;
}
// 判断Key是否为16位
if (sKey.length() != 16) {
System.out.print("Key长度不是16位");
return null;
}
byte[] raw = sKey.getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec(_key);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(sSrc.getBytes()); return byte2hex(encrypted).toLowerCase();
} public static String Decrypt(String sSrc, String sKey) throws Exception {
try {
// 判断Key是否正确
if (sKey == null) {
System.out.print("Key为空null");
return null;
}
// 判断Key是否为16位
if (sKey.length() != 16) {
System.out.print("Key长度不是16位");
return null;
}
byte[] raw = sKey.getBytes("ASCII");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec(_key);
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] encrypted1 = hex2byte(sSrc);
try {
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original);
return originalString;
} catch (Exception e) {
System.out.println(e.toString());
return null;
}
} catch (Exception ex) {
System.out.println(ex.toString());
return null;
}
} public static byte[] hex2byte(String strhex) {
if (strhex == null) {
return null;
}
int l = strhex.length();
if (l % 2 == 1) {
return null;
}
byte[] b = new byte[l / 2];
for (int i = 0; i != l / 2; i++) {
b[i] = (byte) Integer.parseInt(strhex.substring(i * 2, i * 2 + 2),
16);
}
return b;
} public static String byte2hex(byte[] b) {
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
if (stmp.length() == 1) {
hs = hs + "0" + stmp;
} else {
hs = hs + stmp;
}
}
return hs.toUpperCase();
} }

.NET AES加密解密:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks; namespace AES_Dome
{
class Program
{
private static string key = "smkldospdosldaaa";//key,可自行修改
private static string iv = ""; //偏移量,可自行修改
static void Main(string[] args)
{
string encrytpData = Encrypt("abc", key, iv);
Console.WriteLine(encrytpData); string decryptData = Decrypt("5z9WEequVr7qtd+WoxV+Kw==", key, iv);
Console.WriteLine(decryptData); Console.ReadLine();
}
public static string Encrypt(string toEncrypt, string key, string iv)
{
byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);
byte[] ivArray = UTF8Encoding.UTF8.GetBytes(iv);
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt); RijndaelManaged rDel = new RijndaelManaged();
rDel.BlockSize = ;
rDel.KeySize = ;
rDel.FeedbackSize = ;
rDel.Padding = PaddingMode.PKCS7;
rDel.Key = keyArray;
rDel.IV = ivArray;
rDel.Mode = CipherMode.CBC; ICryptoTransform cTransform = rDel.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, , toEncryptArray.Length); return Convert.ToBase64String(resultArray, , resultArray.Length);
} public static string Decrypt(string toDecrypt, string key, string iv)
{
byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);
byte[] ivArray = UTF8Encoding.UTF8.GetBytes(iv);
byte[] toEncryptArray = Convert.FromBase64String(toDecrypt); // 这里的模式,请保持和上面加密的一样。但源代码里,这个地方并没有修正,虽然也能正确解密。看到博客的朋友,请自行修改。
// 这是个人疏忽的地址,感谢@jojoka 的提醒。
RijndaelManaged rDel = new RijndaelManaged();
//rDel.Key = keyArray;
//rDel.IV = ivArray;
//rDel.Mode = CipherMode.CBC;
//rDel.Padding = PaddingMode.Zeros;        rDel.BlockSize = ;
rDel.KeySize = ;
rDel.FeedbackSize = ;
rDel.Padding = PaddingMode.PKCS7;
rDel.Key = keyArray;
rDel.IV = ivArray;
rDel.Mode = CipherMode.CBC;
    ICryptoTransform cTransform = rDel.CreateDecryptor();     byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, , toEncryptArray.Length);     return UTF8Encoding.UTF8.GetString(resultArray);
  }
}
}

二、ECB(Electronic Code Book,电子密码本)模式

是一种基础的加密方式,密文被分割成分组长度相等的块(不足补齐),然后单独一个个加密,一个个输出组成密文。

只需要提供密码即可。

iOS,android,java已调通源码:源码下载

AES在线加解密验证工具: http://www.seacha.com/tools/aes.html