Java、C#双语版配套AES加解密示例

简介:

今天在搞一款手游,使用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

相关文章
|
12月前
|
Java 开发工具
【Azure Storage Account】Java Code访问Storage Account File Share的上传和下载代码示例
本文介绍如何使用Java通过azure-storage-file-share SDK实现Azure文件共享的上传下载。包含依赖引入、客户端创建及完整示例代码,助你快速集成Azure File Share功能。
764 6
|
IDE Java 关系型数据库
Java 初学者学习路线(含代码示例)
本教程为Java初学者设计,涵盖基础语法、面向对象、集合、异常处理、文件操作、多线程、JDBC、Servlet及MyBatis等内容,每阶段配核心代码示例,强调动手实践,助你循序渐进掌握Java编程。
1446 3
|
Java
java入门代码示例
本文介绍Java入门基础,包含Hello World、变量类型、条件判断、循环及方法定义等核心语法示例,帮助初学者快速掌握Java编程基本结构与逻辑。
843 0
Java API 开发者
460 0
|
安全 Java 网络安全
Java 实现 SMTP 协议调用的详细示例及实战指南 SMTP Java 调用示例
本文介绍了如何使用Java调用SMTP协议发送邮件,涵盖SMTP基本概念、JavaMail API配置、代码实现及注意事项,适合Java开发者快速掌握邮件发送功能集成。
1637 0
|
算法 搜索推荐 Java
Java中的Collections.shuffle()方法及示例
`Collections.shuffle()` 是 Java 中用于随机打乱列表顺序的方法,基于 Fisher-Yates 算法实现,支持原地修改。可选传入自定义 `Random` 对象以实现结果可重复,适用于抽奖、游戏、随机抽样等场景。
535 0
|
存储 安全 Java
应届生面试高频 Java 基础问题及实操示例解析
本文总结了Java基础面试中的高频考点,包括数据类型分类、final修饰符的三种用途、static关键字特性、==与equals的区别、Java只有值传递的特性、String的不可变性、Error与Exception的差异、程序初始化顺序规则,以及IO流的字节流/字符流分类。每个问题都配有简明定义和典型示例,如用final修饰变量示例、static方法调用限制说明等,帮助应聘者快速掌握核心概念和实际应用场景。
468 0
|
Java 关系型数据库 MySQL
2025 年互联网公司校招 Java 面试题总结及答案实操示例解析
本项目基于Spring Boot 3与Java 17技术栈,围绕校园招聘常见面试题,提供核心知识点的实操示例。涵盖多线程、RESTful API设计、数据库操作(Spring Data JPA)、事务管理及异常处理等。通过完整代码实现与运行步骤,帮助理解用户管理、线程池配置等实际应用场景。资源包含项目结构、关键代码示例(如User实体类、UserService服务层、ThreadService多线程实现)及数据库迁移脚本,适合深入学习与实践。环境要求:JDK 17+、Maven 3.8+、MySQL 8.0+。
523 3
|
Java
在Java中实现接口的具体代码示例
可以根据具体的需求,创建更多的类来实现这个接口,以满足不同形状的计算需求。希望这个示例对你理解在 Java 中如何实现接口有所帮助。
679 38