在C# 中的AES加密算法
项目背景: 我要用C# 些WCF服务建立服务器端的程序、为安卓客户端提供访问端口,供安卓端和Oracle 、SQL Server 数据库对接执行SQL命令。
字符串的传输为了避免泄漏信息和SQL 注入攻击,采用AES加密算法传递字符串、并采用BASE 64 字符串转义来防止URL对特殊字符的异常。
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 = "1234567890123456";//key,可自行修改
private static string iv = "0000000000000000"; //偏移量,可自行修改
static void Main(string[] args)
{
string encrytpData = Encrypt("SELECT * FROM [MesConfig].[dbo].[SYS_PROGRAM_NAME]", key, iv);
Console.WriteLine(encrytpData);
string B = encrytpData;
//PaddingMode
string decryptData = Decrypt(B, key, iv, PaddingMode.PKCS7);
Console.WriteLine("PKCS7 "+decryptData);
decryptData = Decrypt(B, key, iv, PaddingMode.ANSIX923);
Console.WriteLine("ISO10126 " + 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; //new byte[16]; //不采用密钥,默认采用16个0 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,PaddingMode PM)
{
try
{
byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);
byte[] ivArray = UTF8Encoding.UTF8.GetBytes(iv);
byte[] toEncryptArray = Convert.FromBase64String(toDecrypt);
RijndaelManaged rDel = new RijndaelManaged();
rDel.Key = keyArray;
rDel.IV = ivArray;// new byte[16]; //不采用密钥,默认采用16个0 ivArray;
rDel.Mode = CipherMode.CBC;
rDel.Padding = PM;
ICryptoTransform cTransform = rDel.CreateDecryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
return UTF8Encoding.UTF8.GetString(resultArray);
}
catch (Exception)
{
return "";
}
}
}
}
android AES加密定义
package com.example.aesproject;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class AesUtil {
public static final String VIPARA ="0000000000000000";// "1269571569321021";
public static final String bm ="UTF-8";
/**
* 字节数组转化为大写16进制字符串
*
* @param b
* @return
*/
private static String byte2HexStr(byte[] b) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < b.length; i++) {
String s = Integer.toHexString(b[i] & 0xFF);
if (s.length() == 1) {
sb.append("0");
}
sb.append(s.toUpperCase());
}
return sb.toString();
}
/**
* 16进制字符串转字节数组
*
* @param s
* @return
*/
private static byte[] str2ByteArray(String s) {
int byteArrayLength = s.length() / 2;
byte[] b = new byte[byteArrayLength];
for (int i = 0; i < byteArrayLength; i++) {
byte b0 = (byte) Integer.valueOf(s.substring(i * 2, i * 2 + 2), 16)
.intValue();
b[i] = b0;
}
return b;
}
/**
* AES 加密
*
* @param content
* 明文
* @param password
* 生成秘钥的关键字
* @return
*/
public static String aesEncrypt(String content, String password) {
try {
IvParameterSpec zeroIv = new IvParameterSpec(VIPARA.getBytes());
SecretKeySpec key = new SecretKeySpec(password.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
byte[] encryptedData = cipher.doFinal(content.getBytes(bm));
// return new String(encryptedData,bm);
return Base64.encode(encryptedData);
// return byte2HexStr(encryptedData);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* AES 解密
*
* @param content
* 密文
* @param password
* 生成秘钥的关键字
* @return
*/
public static String aesDecrypt(String content, String password) {
try {
byte[] byteMi = Base64.decode(content);
// byte[] byteMi= str2ByteArray(content);
IvParameterSpec zeroIv = new IvParameterSpec(VIPARA.getBytes());
SecretKeySpec key = new SecretKeySpec(password.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);
byte[] decryptedData = cipher.doFinal(byteMi);
return new String(decryptedData, "utf-8");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
package com.example.aesproject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class Base64 {
private static final char[] legalChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
.toCharArray();
public static String encode(byte[] data) {
int start = 0;
int len = data.length;
StringBuffer buf = new StringBuffer(data.length * 3 / 2);
int end = len - 3;
int i = start;
int n = 0;
while (i <= end) {
int d = ((((int) data[i]) & 0x0ff) << 16) | ((((int) data[i + 1]) & 0x0ff) << 8)
| (((int) data[i + 2]) & 0x0ff);
buf.append(legalChars[(d >> 18) & 63]);
buf.append(legalChars[(d >> 12) & 63]);
buf.append(legalChars[(d >> 6) & 63]);
buf.append(legalChars[d & 63]);
i += 3;
if (n++ >= 14) {
n = 0;
buf.append(" ");
}
}
if (i == start + len - 2) {
int d = ((((int) data[i]) & 0x0ff) << 16) | ((((int) data[i + 1]) & 255) << 8);
buf.append(legalChars[(d >> 18) & 63]);
buf.append(legalChars[(d >> 12) & 63]);
buf.append(legalChars[(d >> 6) & 63]);
buf.append("=");
} else if (i == start + len - 1) {
int d = (((int) data[i]) & 0x0ff) << 16;
buf.append(legalChars[(d >> 18) & 63]);
buf.append(legalChars[(d >> 12) & 63]);
buf.append("==");
}
return buf.toString();
}
private static int decode(char c) {
if (c >= 'A' && c <= 'Z')
return ((int) c) - 65;
else if (c >= 'a' && c <= 'z')
return ((int) c) - 97 + 26;
else if (c >= '0' && c <= '9')
return ((int) c) - 48 + 26 + 26;
else
switch (c) {
case '+':
return 62;
case '/':
return 63;
case '=':
return 0;
default:
throw new RuntimeException("unexpected code: " + c);
}
}
/**
* Decodes the given Base64 encoded String to a new byte array. The byte
* array holding the decoded data is returned.
*/
public static byte[] decode(String s) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
decode(s, bos);
} catch (IOException e) {
throw new RuntimeException();
}
byte[] decodedBytes = bos.toByteArray();
try {
bos.close();
bos = null;
} catch (IOException ex) {
System.err.println("Error while decoding BASE64: " + ex.toString());
}
return decodedBytes;
}
private static void decode(String s, OutputStream os) throws IOException {
int i = 0;
int len = s.length();
while (true) {
while (i < len && s.charAt(i) <= ' ')
i++;
if (i == len)
break;
int tri = (decode(s.charAt(i)) << 18) + (decode(s.charAt(i + 1)) << 12) + (decode(s.charAt(i + 2)) << 6)
+ (decode(s.charAt(i + 3)));
os.write((tri >> 16) & 255);
if (s.charAt(i + 2) == '=')
break;
os.write((tri >> 8) & 255);
if (s.charAt(i + 3) == '=')
break;
os.write(tri & 255);
i += 4;
}
}
}
不懂可以联系我我 [email protected]