import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec; import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException; import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import sun.misc.BASE64Decoder; public class RSAUtils { private static final Logger LOGGER = LoggerFactory.getLogger(RSAUtils.class);
public static final String KEY_ALGORITHM = "RSA";
public static final String CIPHER_ALGORITHM = "RSA/ECB/PKCS1Padding";
public static final String PUBLIC_KEY = "publicKey";
public static final String PRIVATE_KEY = "privateKey";
public static final int KEY_SIZE = 1024;
public static final String PLAIN_TEXT = "MANUTD is the greatest club in the world";
public static final String DEFAULT_PRIVATE_KEY =
"MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBALLzcCAoQaBK3X0cPbsu1xKUsuwQ\n" +
"vtVz12t16ARd2fza5H6A3aekI1DZV/+U6IT7LQm/75uOlTpek7W8nRZJsrxqK523RILCds5UEkGE\n" +
"yM87RulTtL+acMBUg3nPxUQiBKj7W79VNDmxX5pO55d/tlIXl9tldQahykkLNSS8HTLzAgMBAAEC\n" +
"gYAhqBOAmNGu+iWqMDOUDv04a2szZvrdXoo3lddratNi8TBkcow9yWsy+43HbhRFXpBb8xN3qFt8\n" +
"vOj/F1hcJsRMxikzSnnDPtri48mx6esMG2v/Jt+eb5tfk4fTmboXXWRMiSjFG8B6cAaCxEwaykSV\n" +
"CSI4S23aWrnJ9I6tezNDQQJBAPiQ7OqNb1/J7nWsKeWZCLLWYwZK2wCmb+IQZ8WUi4mIUlj6tkBX\n" +
"rD+XAmdK1OXgjLHUlMAM0GZ0NQJfD++FdvECQQC4TYYliyJTjXoWDEBWWaVASRfK7RXBq8JTeXGg\n" +
"5bjQZzJsmfqS5aU8Qz1AZyc9gjXuMJMqszv+WuyQ5vyLHPAjAkEAwvC2PcWqoU83KyZYvW5lugwV\n" +
"IWw3kaz2di8zk2tKfBRjsND/ejrIJh8CjYvMqHSRIy57cpsaHh/pKvDvCIR9oQJBAKGceVFanBMg\n" +
"MDo9K/2MRngEoDR1iWp2rsR77cPlLRayJ2lL7In7jdU2MPPUgHhTQe9H8QS0fpsgJ+k4Y6OpEHkC\n" +
"QBvpHMdDZG9e7+eTeHTss5eZ6MzEA0umVZYrk+9egqDD5bVl11E/A6xoAMzRPsfsBxxaltnXwCyr\n" +
"HjjWbeNVKso=";
public static final String DEFAULT_PUBLIC_KEY =
"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCy83AgKEGgSt19HD27LtcSlLLsEL7Vc9drdegE\n" +
"Xdn82uR+gN2npCNQ2Vf/lOiE+y0Jv++bjpU6XpO1vJ0WSbK8aiudt0SCwnbOVBJBhMjPO0bpU7S/\n" +
"mnDAVIN5z8VEIgSo+1u/VTQ5sV+aTueXf7ZSF5fbZXUGocpJCzUkvB0y8wIDAQAB"; /**
* 获取公钥
* @param publicKeyStr
* @return
* @throws Exception
*/
public static PublicKey loadPublicKey(String publicKeyStr) throws Exception {
try {
BASE64Decoder base64Decoder = new BASE64Decoder();
byte[] buffer = base64Decoder.decodeBuffer(publicKeyStr);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(keySpec);
return restorePublicKey(publicKey.getEncoded()); } catch (NoSuchAlgorithmException e) {
throw new Exception("无此算法");
} catch (InvalidKeySpecException e) {
throw new Exception("公钥非法");
} catch (IOException e) {
throw new Exception("公钥数据内容读取错误");
} catch (NullPointerException e) {
throw new Exception("公钥数据为空");
}
} /**
* 还原公钥,X509EncodedKeySpec 用于构建公钥的规范
*
* @param keyBytes
* @return
*/
public static PublicKey restorePublicKey(byte[] keyBytes) throws Exception {
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);
try {
KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM);
PublicKey publicKey = factory.generatePublic(x509EncodedKeySpec);
return publicKey;
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
// TODO Auto-generated catch block
throw new Exception("");
}
} /**
* 通过私钥KEY获取解密私钥
* @param privateKeyStr
* @return
* @throws Exception
*/
public static PrivateKey loadPrivateKey(String privateKeyStr) throws Exception {
try {
BASE64Decoder base64Decoder = new BASE64Decoder();
byte[] buffer = base64Decoder.decodeBuffer(privateKeyStr);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
return restorePrivateKey(privateKey.getEncoded()); } catch (NoSuchAlgorithmException e) {
throw new Exception("无此算法");
} catch (InvalidKeySpecException e) {
throw new Exception("公钥非法");
} catch (IOException e) {
throw new Exception("公钥数据内容读取错误");
} catch (NullPointerException e) {
throw new Exception("公钥数据为空");
}
} /**
* 获取私钥
* @param keyBytes
* @return
*/
public static PrivateKey restorePrivateKey(byte[] keyBytes) {
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);
try {
KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM);
PrivateKey privateKey = factory.generatePrivate(pkcs8EncodedKeySpec);
return privateKey;
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
// TODO Auto-generated catch block
LOGGER.error("获取私钥失败", e);
}
return null;
} /**
* 加密,三步走。
*
* @param key
* @param plainText
* @return
*/
public static byte[] RSAEncode(PublicKey key, byte[] plainText) { try {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key);
return cipher.doFinal(plainText);
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
// TODO Auto-generated catch block
LOGGER.error("加密失败", e);
}
return null; } /**
* 解密,三步走。
*
* @param key
* @param encodedText
* @return
*/
public static byte[] RSADecode(PrivateKey key, byte[] encodedText) { try {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key);
return cipher.doFinal(encodedText);
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
// TODO Auto-generated catch block
LOGGER.error("解密失败", e);
}
return null; } public static void main(String[] ar) throws Exception {
String str = "{\"a\":\"欢迎来到chacuo\"}";
System.out.println("待加密报文:" + str);
PublicKey publicKey = loadPublicKey(DEFAULT_PUBLIC_KEY);
PrivateKey privateKey = loadPrivateKey(DEFAULT_PRIVATE_KEY);
// String encodeStr = Base64.encodeBase64String(RSAEncode(publicKey, str.getBytes()));
// System.out.println("加密后密文:" + encodeStr);
// String decodeStr = new String(RSADecode(privateKey, Base64.decodeBase64(encodeStr)));
// System.out.println("解密后密文:" + decodeStr); String randomKey = String.valueOf(System.currentTimeMillis());
System.out.println("随机KEY randomKey:"+randomKey); String cipherText = AESUtils.encrypt(str,randomKey);
System.out.println("AES加密请求内容cipherText:"+cipherText); String cipherKey = Base64.encodeBase64String(RSAEncode(publicKey, randomKey.getBytes()));
System.out.println("RSA加密后的key:"+cipherKey); System.out.println("请求内容:{\"encryptStr\":\"" + cipherText+"\",\"aesKey\":\""+cipherKey+"\"}"); String key = new String(RSADecode(privateKey, Base64.decodeBase64(cipherKey)));
System.out.println("RSA私钥解密后的key:"+key); String decodeData = AESUtils.decrypt(cipherText,key);
System.out.println("AES解密后:"+decodeData);
}
}

RSAUtils

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom; /**
* @Auther: yaojiewen
* @Date: 2018/6/1 *
*/
public class AESUtils{ private static final Logger LOGGER = LoggerFactory.getLogger(AESUtils.class);
private static final String KEY_ALGORITHM = "AES";
private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";//默认的加密算法 /**
* AES 加密操作
*
* @param content 待加密内容
* @param password 加密密码
* @return 返回Base64转码后的加密数据
*/
public static String encrypt(String content, String password) {
try {
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);// 创建密码器
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(password));// 初始化为加密模式的密码器
byte[] result = cipher.doFinal(byteContent);// 加密
return Base64.encodeBase64String(result);//通过Base64转码返回
} catch (Exception ex) {
LOGGER.error("加密失败",ex);
}
return null;
} /**
* AES 解密操作
*
* @param content
* @param password
* @return
*/
public static String decrypt(String content, String password) {
try {
//实例化
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
//使用密钥初始化,设置为解密模式
cipher.init(Cipher.DECRYPT_MODE, getSecretKey(password));
//执行操作
byte[] result = cipher.doFinal(Base64.decodeBase64(content));
return new String(result, "utf-8");
} catch (Exception ex) {
LOGGER.error("解密失败",ex);
}
return null;
} /**
* 生成加密秘钥
*
* @return
*/
private static SecretKeySpec getSecretKey(final String password) {
//返回生成指定算法密钥生成器的 KeyGenerator 对象
KeyGenerator kg = null;
try {
kg = KeyGenerator.getInstance(KEY_ALGORITHM);
//AES 要求密钥长度为 128
kg.init(128, new SecureRandom(password.getBytes()));
//生成一个密钥
SecretKey secretKey = kg.generateKey();
return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);// 转换为AES专用密钥
} catch (NoSuchAlgorithmException ex) {
LOGGER.error("生成密钥失败",ex);
} return null;
} public static void main(String[] args) {
String s = "欢迎来到chacuo.net"; System.out.println("s:" + s); String s1 = AESUtils.encrypt(s, "1234");
System.out.println("s1:" + s1); System.out.println("s2:"+AESUtils.decrypt("fJEvvBjcnAkkWM+G6SugKViuBn26Wd7n4RBGCZheERU=", "1234")); }
}

AESUtils

AES与RAS结合加解密方案的更多相关文章

  1. AES ECB PKCS5/PKCS7 加解密 python实现 支持中文

    目录 ECB模式介绍 pkcs5padding和pkcs7padding的区别 python实现 注意事项 ECB模式介绍 电码本模式(Electronic Codebook Book (ECB) 这 ...

  2. C#与 微信小程序 互为加解密方案

    CryptoJS下载地址: https://code.google.com/archive/p/crypto-js/downloads http://download.csdn.net/detail/ ...

  3. [编码解码] 关于AES加解密中CBC模式的IV初始化向量的安全性问题

    copy from : https://www.jianshu.com/p/45848dd484a9 前段时间,在研究HLS的AES加密,由于一个地方电视台的HLS流有AES加密,在查看了相关的加解密 ...

  4. Aes加解密,php

    Aes类库 <?php namespace Aes; class Aes { /** * var string $method 加解密方法,可通过openssl_get_cipher_metho ...

  5. React中的AES加解密请求

    引言 在我们使用React开发Web前端的时候,如果是比较大的项目和正常的项目的话,我们必然会用到加解密,之前的文章中提到.NET的一些加解密,那么,这里我就模拟一个例子: 1.后台开发API接口,但 ...

  6. 微信消息体加解密及EncodingAESKey

    公众平台消息体签名及加解密方案概述 1.新增消息体签名验证,用于公众平台和公众账号验证消息体的正确性 2.针对推送给微信公众账号的普通消息和事件消息,以及推送给设备公众账号的设备消息进行加密 3.公众 ...

  7. 惊呆了!不改一行 Java 代码竟然就能轻松解决敏感信息加解密|原创

    前言 出于安全考虑,现需要将数据库的中敏感信息加密存储到数据库中,但是正常业务交互还是需要使用明文数据,所以查询返回我们还需要经过相应的解密才能返回给调用方. ps:日常开发中,我们要有一定的安全意识 ...

  8. SpringBoot+ShardingSphere彻底解决生产环境数据库字段加解密问题

    前言   互联网行业公司,对于数据库的敏感字段是一定要进行加密的,方案有很多,最直接的比如写个加解密的工具类,然后在每个业务逻辑中手动处理,在稍微有点规模的项目中这种方式显然是不现实的,不仅工作量大而 ...

  9. C# AESCBC256 与 java AESCBC256 加解密

    和某上市公司对接接口,他们试用 java AES CBC PKCS5 256 加解密.网上C# 基本不合适. 注意:C# PKCS7 对应 java PKCS5 /// <summary> ...

随机推荐

  1. HDU-1878 欧拉回路 欧拉回路

    题目链接:https://cn.vjudge.net/problem/HDU-1878 题意 中文题,而且就是单纯的欧拉回路 思路 判断连通图 用并查集会很好,bfs亦可 一时脑抽用bfs过了这个题, ...

  2. C语言之基本算法26—佩尔方程求解

    //穷举法! /* ====================================================== 题目:求佩尔方程x*x-73*y*y=1的解. =========== ...

  3. 4.graph.h

    #pragma once #include <stdio.h> #include <graphics.h> #include <mmsystem.h> #pragm ...

  4. BZOJ 4385 单调队列

    思路: 对于每一个r 要找最小的符合条件的l最优 这时候就要找在这个区间中 d长度的和的最大值 用单调队列更新就好了 //By SiriusRen #include <cstdio> #i ...

  5. spring-cloud-netflix集成的服务

    1.Ribbon Ribbon is a client side IPC library that is battle-tested in cloud. It provides the followi ...

  6. C# double保留四位小数

    2.保留N位,四舍五入 . decimal d= decimal.Round(decimal.Parse("0.55555"),4); 3.保留N位四舍五入 Math.Round( ...

  7. linux下支持托盘的邮件客户端Sylpheed

    在网上搜索了很多客户端想支持系统托盘,发现一个很不错的邮件客户端Sylpheed.设置方式和foxmail很像,最为重要的是支持系统托盘,很方便,默认没有开启,简单设置下:配置->通用首选项-& ...

  8. monyer教你玩电脑——CSS、HTML、JS、XML的关系

    首先Monyer还是有必要提一句:这是一篇低中等难度的文章.如果你是高手或被认为是高手,那么请pass掉这篇文章:如果你是新手,甚至不知道什么是css(譬如百度模版)等,那么请pass掉这篇文章.谢谢 ...

  9. 应用层协议——HTTP

    HTTP: Client HTTP <--> 应用程序HTTP报文 <--> Server HTTP 应用程序 由TCP支持 Statelessprotocol:不会记录客户端 ...

  10. 【Django】Web框架本质

    目录 根据不同的路径返回不同的内容 普通版 函数版 函数进阶版 返回具体的HTML文件 让网页动态起来 服务器和应用程序 wsgiref 模块 @ * 我们可以这样理解:所有的==Web应用本质上就是 ...