移動端越來越火了,我們在開發過程中,總會碰到要和移動端打交道的場景,比如.NET和android或者iOS的打交道。為了讓數據交互更安全,我們需要對數據進行加密傳輸。今天研究了一下,把幾種語言的加密都實踐了一遍,實現了.NET,java(android),iOS都同一套的加密算法,下面就分享給大家。
AES加密有多種算法模式,下面提供兩套模式的可用源碼。
加密方式:
- 先將文本AES加密
- 返回Base64轉碼
解密方式:
- 將數據進行Base64解碼
- 進行AES解密
一、CBC(Cipher Block Chaining,加密塊鏈)模式
是一種循環模式,前一個分組的密文和當前分組的明文異或操作后再加密,這樣做的目的是增強破解難度.
- 密鑰
- 密鑰偏移量
java/adroid加密AESOperator類:
package com.bci.wx.base.util; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import sun.misc.BASE64Decoder; 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")); 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")); 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 + "毫秒"); } }
.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 = "0392039203920300"; //偏移量,可自行修改 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 = 128; rDel.KeySize = 256; rDel.FeedbackSize = 128; rDel.Padding = PaddingMode.PKCS7; rDel.Key = keyArray; rDel.IV = ivArray; rDel.Mode = CipherMode.CBC; ICryptoTransform cTransform = rDel.CreateEncryptor(); byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return Convert.ToBase64String(resultArray, 0, 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 = 128; rDel.KeySize = 256; rDel.FeedbackSize = 128; rDel.Padding = PaddingMode.PKCS7; rDel.Key = keyArray; rDel.IV = ivArray; rDel.Mode = CipherMode.CBC;
ICryptoTransform cTransform = rDel.CreateDecryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
return UTF8Encoding.UTF8.GetString(resultArray);
}
}
}
iOS源碼,請下載源碼,源碼里有包含。
java,.net,iOS,android通用AES加密解密源碼:點擊下載
二、ECB(Electronic Code Book,電子密碼本)模式
是一種基礎的加密方式,密文被分割成分組長度相等的塊(不足補齊),然后單獨一個個加密,一個個輸出組成密文。
只需要提供密碼即可。
iOS,android,java已調通源碼:源碼下載
AES在線加解密驗證工具: http://www.seacha.com/tools/aes.html