今天在搞一款手游,使用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 = "\n";
for(int i=0;i<value.length;i++)
{
s += value[i];
s += ",";
}
return s;
}
}
复制代码
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
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 + "\n";
string d = AES.AESDecrypt(e);
Debug.Log("d:" + d);
//text.GetComponent<Text>().text += d + "\n";
}
// 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;
///
/// 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;
}
}
本文转自jiahuafu博客园博客,原文链接http://www.cnblogs.com/jiahuafu/p/6475277.html如需转载请自行联系原作者
jiahuafu