今天在搞一款手游,使用U3D,遇到一个字符串加解密的功能需求
客户端和服务器在通迅时的一个加解密的验证
JAVA
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package teststring;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
/**
*
* @author Acer
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException, Exception {
// TODO code application logic here
String e;
String d;
try {
e = AES.AESEncrypt("fdafdsaff2fwe23fdsa9");
System.out.println(e);
d = AES.AESDecrypt(e);
System.out.println(d);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchPaddingException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidKeyException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidAlgorithmParameterException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalBlockSizeException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (BadPaddingException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
System.in.read();
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package teststring;
import java.nio.charset.Charset;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
/**
*
* @author Acer
*/
public class AES {
private static String Key()
{
return "1234567812345678";
}
private static String IV()
{
return "1234567812345678";
}
/**
*
*
* @param plainStr
* @return
* @throws NoSuchAlgorithmException
* @throws NoSuchPaddingException
*/
public static String AESEncrypt(String plainStr) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException
{
byte[] ks = Key().getBytes(Charset.forName("UTF-8"));
//System.out.println(printByte(ks));
byte[] iv = IV().getBytes(Charset.forName("UTF-8"));
//System.out.println(printByte(iv));
byte[] ps = plainStr.getBytes(Charset.forName("UTF-8"));
//System.out.println(printByte(ps));
Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec keySpec = new SecretKeySpec(ks,"AES");
AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
c.init(Cipher.ENCRYPT_MODE, keySpec,ivSpec);
byte[] mStream = c.doFinal(ps);
String encrypt;
encrypt = new Base64().encodeToString(mStream);//printByte(mStream);//
return encrypt;
}
public static String AESDecrypt(String encryptStr) throws Exception
{
Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] ks = Key().getBytes(Charset.forName("UTF-8"));
SecretKeySpec keySpec = new SecretKeySpec(ks,"AES");
byte[] iv = IV().getBytes(Charset.forName("UTF-8"));
AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
c.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
byte[] bytes = new Base64().decode(encryptStr);
bytes = c.doFinal(bytes);
return new String(bytes, "UTF-8");
}
public static String printByte(byte[] value)
{
String s = "
";
for(int i=0;i<value.length;i++)
{
s += value[i];
s += ",";
}
return s;
}
}
C#
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class TestAES : MonoBehaviour {
// Use this for initialization
void Start () {
GameObject text = GameObject.Find("Canvas/Text");
string e = AES.AESEncrypt("fdafdsaff2fwe23fdsa9");
Debug.Log("e:" + e);
text.GetComponent<Text>().text += e + "
";
string d = AES.AESDecrypt(e);
Debug.Log("d:" + d);
//text.GetComponent<Text>().text += d + "
";
}
// Update is called once per frame
void Update () {
}
}
using UnityEngine;
using System.Collections;
using System.Text;
using System;
using System.Security.Cryptography;
using System.IO;
/// <summary>
/// AES加密解密
/// </summary>
public class AES
{
/// <summary>
/// 获取密钥
/// </summary>
private static string Key
{
get { return @"1234567812345678"; }
}
/// <summary>
/// 获取向量
/// </summary>
private static string IV
{
get { return @"1234567812345678"; }
}
/// <summary>
/// AES加密
/// </summary>
/// <param name="plainStr">明文字符串</param>
/// <returns>密文</returns>
public static string AESEncrypt(string plainStr)
{
byte[] bKey = Encoding.UTF8.GetBytes(Key);
Debug.Log(printByte(bKey));
byte[] bIV = Encoding.UTF8.GetBytes(IV);
Debug.Log(printByte(bIV));
byte[] byteArray = Encoding.UTF8.GetBytes(plainStr);
Debug.Log(printByte(byteArray));
string encrypt = null;
Rijndael aes = Rijndael.Create();
try
{
using (MemoryStream mStream = new MemoryStream())
{
using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateEncryptor(bKey, bIV), CryptoStreamMode.Write))
{
cStream.Write(byteArray, 0, byteArray.Length);
cStream.FlushFinalBlock();
byte[] bb = mStream.ToArray();
encrypt = Convert.ToBase64String(bb);//printByte(bb);//
}
}
}
catch(Exception exd)
{
Debug.Log("Exception :AESEncrypt " + exd.Message);
}
aes.Clear();
return encrypt;
}
/// <summary>
/// AES加密
/// </summary>
/// <param name="plainStr">明文字符串</param>
/// <param name="returnNull">加密失败时是否返回 null,false 返回 String.Empty</param>
/// <returns>密文</returns>
public static string AESEncrypt(string plainStr, bool returnNull)
{
string encrypt = AESEncrypt(plainStr);
return returnNull ? encrypt : (encrypt == null ? String.Empty : encrypt);
}
/// <summary>
/// AES解密
/// </summary>
/// <param name="encryptStr">密文字符串</param>
/// <returns>明文</returns>
public static string AESDecrypt(string encryptStr)
{
byte[] bKey = Encoding.UTF8.GetBytes(Key);
byte[] bIV = Encoding.UTF8.GetBytes(IV);
byte[] byteArray = Convert.FromBase64String(encryptStr);
string decrypt = null;
Rijndael aes = Rijndael.Create();
try
{
using (MemoryStream mStream = new MemoryStream())
{
using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateDecryptor(bKey, bIV), CryptoStreamMode.Write))
{
cStream.Write(byteArray, 0, byteArray.Length);
cStream.FlushFinalBlock();
decrypt = Encoding.UTF8.GetString(mStream.ToArray());
}
}
}
catch { }
aes.Clear();
return decrypt;
}
/// <summary>
/// AES解密
/// </summary>
/// <param name="encryptStr">密文字符串</param>
/// <param name="returnNull">解密失败时是否返回 null,false 返回 String.Empty</param>
/// <returns>明文</returns>
public static string AESDecrypt(string encryptStr, bool returnNull)
{
string decrypt = AESDecrypt(encryptStr);
return returnNull ? decrypt : (decrypt == null ? String.Empty : decrypt);
}
public static string printByte(byte[] value)
{
string s = string.Empty;
for(int i=0;i<value.Length;i++)
{
s += value[i];
s += ",";
}
return s;
}
}