话不多数上代码;

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 com.totcms.api.util; import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec; import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey; public class AES {
// /** 算法/模式/填充 **/
private static final String CipherMode = "AES/ECB/PKCS5Padding";
// private static final String CipherMode = "AES"; /**
* 生成一个AES密钥对象
* @return
*/
public static SecretKeySpec generateKey(){
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom());
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
return key;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
} /**
* 生成一个AES密钥字符串
* @return
*/
public static String generateKeyString(){
return byte2hex(generateKey().getEncoded());
} /**
* 加密字节数据
* @param content
* @param key
* @return
*/
public static byte[] encrypt(byte[] content,byte[] key) {
try {
Cipher cipher = Cipher.getInstance(CipherMode);
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"));
byte[] result = cipher.doFinal(content);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
} /**
* 通过byte[]类型的密钥加密String
* @param content
* @param key
* @return 16进制密文字符串
*/
public static String encrypt(String content,byte[] key) {
try {
Cipher cipher = Cipher.getInstance(CipherMode);
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"));
byte[] data = cipher.doFinal(content.getBytes("UTF-8"));
String result = byte2hex(data);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
} /**
* 通过String类型的密钥加密String
* @param content
* @param key
* @return 16进制密文字符串
*/
public static String encrypt(String content,String key) {
byte[] data = null;
try {
data = content.getBytes("UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
data = encrypt(data,new SecretKeySpec(hex2byte(key), "AES").getEncoded());
String result = byte2hex(data);
return result;
} /**
* 通过byte[]类型的密钥解密byte[]
* @param content
* @param key
* @return
*/
public static byte[] decrypt(byte[] content,byte[] key) {
try {
Cipher cipher = Cipher.getInstance(CipherMode);
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"));
byte[] result = cipher.doFinal(content);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
} /**
* 通过String类型的密钥 解密String类型的密文
* @param content
* @param key
* @return
*/
public static String decrypt(String content, String key) {
byte[] data = null;
try {
data = hex2byte(content);
} catch (Exception e) {
e.printStackTrace();
}
data = decrypt(data, hex2byte(key));
if (data == null)
return null;
String result = null;
try {
result = new String(data, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
} /**
* 通过byte[]类型的密钥 解密String类型的密文
* @param content
* @param key
* @return
*/
public static String decrypt(String content,byte[] key) {
try {
Cipher cipher = Cipher.getInstance(CipherMode);
cipher.init(Cipher.DECRYPT_MODE,new SecretKeySpec(key, "AES"));
byte[] data = cipher.doFinal(hex2byte(content));
return new String(data, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
return null;
} /**
* 字节数组转成16进制字符串
* @param b
* @return
*/
public static String byte2hex(byte[] b) { // 一个字节的数,
StringBuffer sb = new StringBuffer(b.length * 2);
String tmp;
for (int n = 0; n < b.length; n++) {
// 整数转成十六进制表示
tmp = (Integer.toHexString(b[n] & 0XFF));
if (tmp.length() == 1) {
sb.append("0");
}
sb.append(tmp);
}
return sb.toString().toUpperCase(); // 转成大写
} /**
* 将hex字符串转换成字节数组
* @param inputString
* @return
*/
private static byte[] hex2byte(String inputString) {
if (inputString == null || inputString.length() < 2) {
return new byte[0];
}
inputString = inputString.toLowerCase();
int l = inputString.length() / 2;
byte[] result = new byte[l];
for (int i = 0; i < l; ++i) {
String tmp = inputString.substring(2 * i, 2 * i + 2);
result[i] = (byte) (Integer.parseInt(tmp, 16) & 0xFF);
}
return result;
} public static void main(String[] args) {
try{
// 加载RSA
//RSAPublicKey publicKey = RSA.loadPublicKey(new FileInputStream("E:\\2016\\9\\19\\cert\\apiclient_cert.p12"));
//RSAPrivateKey privateKey = RSA.loadPrivateKey(new FileInputStream("E:\\2016\\9\\19\\cert\\apiclient_cert.p12")); // 生成AES密钥
String key=AES.generateKeyString();
// String key = "1234567890123456";
System.out.println("AES-KEY:" + key); // 内容
// String content = "{\"mobile\":\"18660803982\",\"amount\":\"100\",\"companyId\":\"8\",\"orderNum\":\"123456789\",\"bussissId\":\"18154568754\",\"notifyUrl\":\"\"}";
String content = "{\"mobile\":\"15005414383\",\"amount\":\"10\",\"companyId\":\"8\",\"orderNum\":\"123456789\",\"notifyUrl\":\"\",\"bussissId\":\"1101\"}"; // 用RSA公钥加密AES-KEY
//String miKey = RSA.encryptByPublicKey(key, publicKey);
//System.out.println("加密后的AES-KEY:" + miKey);
//System.out.println("加密后的AES-KEY长度:" + miKey.length()); // 用RSA私钥解密AES-KEY
//String mingKey = RSA.decryptByPrivateKey(miKey, privateKey);
//System.out.println("解密后的AES-KEY:" + mingKey);
//System.out.println("解密后的AES-KEY长度:" + mingKey.length()); // 用AES加密内容
//String miContent = AES.encrypt(content, mingKey);
String miContent = AES.encrypt(content, "6369BE91F580F990015D709D4D69FA41");
System.out.println("AES加密后的内容:" + miContent);
// 用AES解密内容
String mingContent = AES.decrypt(miContent, "6369BE91F580F990015D709D4D69FA41");
System.out.println("AES解密后的内容:" + mingContent);
}catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
} }
}

.net  ;;

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Web;
using System.Text.RegularExpressions;
using System.Security.Cryptography; namespace PostDemo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} public static string AESEncrypts(String Data, String Key)
{
// 256-AES key
byte[] keyArray = HexStringToBytes(Key);//UTF8Encoding.ASCII.GetBytes(Key);
byte[] toEncryptArray = UTF8Encoding.ASCII.GetBytes(Data); RijndaelManaged rDel = new RijndaelManaged();
rDel.Key = keyArray;
rDel.Mode = CipherMode.ECB;
rDel.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = rDel.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0,
toEncryptArray.Length); return BytesToHexString(resultArray);
} /// <summary>
/// Byte array to convert 16 hex string
/// </summary>
/// <param name="bytes">byte array</param>
/// <returns>16 hex string</returns>
public static string BytesToHexString(byte[] bytes)
{
StringBuilder returnStr = new StringBuilder();
if (bytes != null || bytes.Length == 0)
{
for (int i = 0; i < bytes.Length; i++)
{
returnStr.Append(bytes[i].ToString("X2"));
}
}
return returnStr.ToString();
} /// <summary>
/// 16 hex string converted to byte array
/// </summary>
/// <param name="hexString">16 hex string</param>
/// <returns>byte array</returns>
public static byte[] HexStringToBytes(String hexString)
{
if (hexString == null || hexString.Equals(""))
{
return null;
}
int length = hexString.Length / 2;
if (hexString.Length % 2 != 0)
{
return null;
}
byte[] d = new byte[length];
for (int i = 0; i < length; i++)
{
d[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
}
return d;
} private void button2_Click(object sender, EventArgs e)
{
String Content = tbContent.Text;//要加密的字符串
//接口密钥,替换成您的密钥(32位)
String k = "6D6A39C7078F6783E561B0D1A9EB2E68";
String s = AESEncrypts(Content, k);
tbLog.AppendText("encript:"+s);
}
}
}

PHP;;

<?php
class CryptAES
{
protected $cipher = MCRYPT_RIJNDAEL_128;
protected $mode = MCRYPT_MODE_ECB;
protected $pad_method = NULL;
protected $secret_key = '';
protected $iv = ''; public function set_cipher($cipher)
{
$this->cipher = $cipher;
} public function set_mode($mode)
{
$this->mode = $mode;
} public function set_iv($iv)
{
$this->iv = $iv;
} public function set_key($key)
{
$this->secret_key = $key;
} public function require_pkcs5()
{
$this->pad_method = 'pkcs5';
} protected function pad_or_unpad($str, $ext)
{
if ( is_null($this->pad_method) )
{
return $str;
}
else
{
$func_name = __CLASS__ . '::' . $this->pad_method . '_' . $ext . 'pad';
if ( is_callable($func_name) )
{
$size = mcrypt_get_block_size($this->cipher, $this->mode);
return call_user_func($func_name, $str, $size);
}
}
return $str;
} protected function pad($str)
{
return $this->pad_or_unpad($str, '');
} protected function unpad($str)
{
return $this->pad_or_unpad($str, 'un');
} public function encrypt($str)
{
$str = $this->pad($str);
$td = mcrypt_module_open($this->cipher, '', $this->mode, ''); if ( empty($this->iv) )
{
$iv = @mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
}
else
{
$iv = $this->iv;
} mcrypt_generic_init($td, hex2bin($this->secret_key), $iv);
$cyper_text = mcrypt_generic($td, $str);
$rt = strtoupper(bin2hex($cyper_text));
mcrypt_generic_deinit($td);
mcrypt_module_close($td); return $rt;
} public function decrypt($str){
$td = mcrypt_module_open($this->cipher, '', $this->mode, ''); if ( empty($this->iv) )
{
$iv = @mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
}
else
{
$iv = $this->iv;
} mcrypt_generic_init($td, $this->secret_key, $iv);
//$decrypted_text = mdecrypt_generic($td, self::hex2bin($str));
$decrypted_text = mdecrypt_generic($td, base64_decode($str));
$rt = $decrypted_text;
mcrypt_generic_deinit($td);
mcrypt_module_close($td); return $this->unpad($rt);
} public static function hex2bin($hexdata) {
$bindata = '';
$length = strlen($hexdata);
for ($i=0; $i< $length; $i += 2)
{
$bindata .= chr(hexdec(substr($hexdata, $i, 2)));
}
return $bindata;
} public static function pkcs5_pad($text, $blocksize)
{
$pad = $blocksize - (strlen($text) % $blocksize);
return $text . str_repeat(chr($pad), $pad);
} public static function pkcs5_unpad($text)
{
$pad = ord($text{strlen($text) - 1});
if ($pad > strlen($text)) return false;
if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) return false;
return substr($text, 0, -1 * $pad);
}
} //密钥
$keyStr = '6D6A39C7078F6783E561B0D1A9EB2E68';
//加密的字符串
$plainText = 'test'; $aes = new CryptAES();
$aes->set_key($keyStr);
$aes->require_pkcs5();
$encText = $aes->encrypt($plainText); echo $encText; ?>
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Windows.Forms;
  9. using System.IO;
  10. using System.Net;
  11. using System.Web;
  12. using System.Text.RegularExpressions;
  13. using System.Security.Cryptography;
  14. namespace PostDemo
  15. {
  16. public partial class Form1 : Form
  17. {
  18. public Form1()
  19. {
  20. InitializeComponent();
  21. }
  22. public static string AESEncrypts(String Data, String Key)
  23. {
  24. // 256-AES key
  25. byte[] keyArray = HexStringToBytes(Key);//UTF8Encoding.ASCII.GetBytes(Key);
  26. byte[] toEncryptArray = UTF8Encoding.ASCII.GetBytes(Data);
  27. RijndaelManaged rDel = new RijndaelManaged();
  28. rDel.Key = keyArray;
  29. rDel.Mode = CipherMode.ECB;
  30. rDel.Padding = PaddingMode.PKCS7;
  31. ICryptoTransform cTransform = rDel.CreateEncryptor();
  32. byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0,
  33. toEncryptArray.Length);
  34. return BytesToHexString(resultArray);
  35. }
  36. /// <summary>
  37. /// Byte array to convert 16 hex string
  38. /// </summary>
  39. /// <param name="bytes">byte array</param>
  40. /// <returns>16 hex string</returns>
  41. public static string BytesToHexString(byte[] bytes)
  42. {
  43. StringBuilder returnStr = new StringBuilder();
  44. if (bytes != null || bytes.Length == 0)
  45. {
  46. for (int i = 0; i < bytes.Length; i++)
  47. {
  48. returnStr.Append(bytes[i].ToString("X2"));
  49. }
  50. }
  51. return returnStr.ToString();
  52. }
  53. /// <summary>
  54. /// 16 hex string converted to byte array
  55. /// </summary>
  56. /// <param name="hexString">16 hex string</param>
  57. /// <returns>byte array</returns>
  58. public static byte[] HexStringToBytes(String hexString)
  59. {
  60. if (hexString == null || hexString.Equals(""))
  61. {
  62. return null;
  63. }
  64. int length = hexString.Length / 2;
  65. if (hexString.Length % 2 != 0)
  66. {
  67. return null;
  68. }
  69. byte[] d = new byte[length];
  70. for (int i = 0; i < length; i++)
  71. {
  72. d[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
  73. }
  74. return d;
  75. }
  76. private void button2_Click(object sender, EventArgs e)
  77. {
  78. String Content = tbContent.Text;//要加密的字符串
  79. //接口密钥,替换成您的密钥(32位)
  80. String k = "6D6A39C7078F6783E561B0D1A9EB2E68";
  81. String s = AESEncrypts(Content, k);
  82. tbLog.AppendText("encript:"+s);
  83. }
  84. }
  85. }

最新文章

  1. Mac OS使用brew安装Nginx、MySQL、PHP-FPM的LAMP开发环境
  2. SSD硬盘的4K对齐
  3. 使用SQL Server维护计划实现数据库定时自动备份
  4. C++ Primer 学习笔记_76_模板与泛型编程 --模板定义[续]
  5. 武汉科技大学ACM:1004: 华科版C语言程序设计教程(第二版)习题5.6
  6. MYSQL连接字符串参数详细解析(大全参考)
  7. 数据分析系统DIY3/3:本地64位WIN7+matlab 2012b訪问VMware CentOS7+MariaDB
  8. Qt移动版优化后台云服务、支持跨平台开发
  9. JS模式--装饰者模式(用AOP动态改变函数的参数)
  10. Java.lang.Comparable接口和Java.util.Comparator接口的区别
  11. [Educational Round 10][Codeforces 652F. Ants on a Circle]
  12. jbe 可以用来修改Java class的字节码,配合jd-gui 使用
  13. pytest使用简介
  14. Mapped Statements collection already contains value for ***.***的问题
  15. odoo8 和odoo10区别
  16. 洛谷 P1141 01迷宫
  17. CSS 隐藏页面元素的 几 种方法总结
  18. os &amp; sys
  19. idea单元测试左侧装订线中的颜色指示器设置
  20. Java异常---获取异常的堆栈信息

热门文章

  1. 2019-8-28-WPF-开发
  2. shell脚本 set命令
  3. python使用SMTP发邮件时使用Cc(抄送)和Bcc(密送)
  4. Codeforces - 1139D - Steps to One (概率DP+莫比乌斯反演)
  5. 前端学习(十四)js回顾和定时器(笔记)
  6. vector注意事项
  7. mysql 毫秒时间转换
  8. 后端获取前端的多个数据用getlist
  9. Shiro学习(12)与Spring集成
  10. ac自动机fail树上按询问建立上跳指针——cf963D