JAVA RSA加密AES加密
RSA加密:
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder; import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map; /**
* Created by xiang.li on 2015/3/3.
* RSA 加解密工具类
*/
public class RSAEncrypt {
/**
* 定义加密方式
*/
private final static String KEY_RSA = "RSA";
/**
* 定义签名算法
*/
private final static String KEY_RSA_SIGNATURE = "MD5withRSA";
/**
* 定义公钥算法
*/
private final static String KEY_RSA_PUBLICKEY = "RSAPublicKey";
/**
* 定义私钥算法
*/
private final static String KEY_RSA_PRIVATEKEY = "RSAPrivateKey"; /**
* 初始化密钥
* @return
*/
public static Map<String, Object> init() {
Map<String, Object> map = null;
try {
KeyPairGenerator generator = KeyPairGenerator.getInstance(KEY_RSA);
generator.initialize(1024);
KeyPair keyPair = generator.generateKeyPair();
// 公钥
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
// 私钥
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
// 将密钥封装为map
map = new HashMap();
map.put(KEY_RSA_PUBLICKEY, publicKey);
map.put(KEY_RSA_PRIVATEKEY, privateKey);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return map;
} /**
* 用私钥对信息生成数字签名
* @param data 加密数据
* @param privateKey 私钥
* @return
*/
public static String sign(byte[] data, String privateKey) {
String str = "";
try {
// 解密由base64编码的私钥
byte[] bytes = decryptBase64(privateKey);
// 构造PKCS8EncodedKeySpec对象
PKCS8EncodedKeySpec pkcs = new PKCS8EncodedKeySpec(bytes);
// 指定的加密算法
KeyFactory factory = KeyFactory.getInstance(KEY_RSA);
// 取私钥对象
PrivateKey key = factory.generatePrivate(pkcs);
// 用私钥对信息生成数字签名
Signature signature = Signature.getInstance(KEY_RSA_SIGNATURE);
signature.initSign(key);
signature.update(data);
str = encryptBase64(signature.sign());
} catch (Exception e) {
e.printStackTrace();
}
return str;
} /**
* 校验数字签名
* @param data 加密数据
* @param publicKey 公钥
* @param sign 数字签名
* @return 校验成功返回true,失败返回false
*/
public static boolean verify(byte[] data, String publicKey, String sign) {
boolean flag = false;
try {
// 解密由base64编码的公钥
byte[] bytes = decryptBase64(publicKey);
// 构造X509EncodedKeySpec对象
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
// 指定的加密算法
KeyFactory factory = KeyFactory.getInstance(KEY_RSA);
// 取公钥对象
PublicKey key = factory.generatePublic(keySpec);
// 用公钥验证数字签名
Signature signature = Signature.getInstance(KEY_RSA_SIGNATURE);
signature.initVerify(key);
signature.update(data);
flag = signature.verify(decryptBase64(sign));
} catch (Exception e) {
e.printStackTrace();
}
return flag;
} /**
* 私钥解密
* @param data 加密数据
* @param key 私钥
* @return
*/
public static byte[] decryptByPrivateKey(byte[] data, String key) {
byte[] result = null;
try {
// 对私钥解密
byte[] bytes = decryptBase64(key);
// 取得私钥
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes);
KeyFactory factory = KeyFactory.getInstance(KEY_RSA);
PrivateKey privateKey = factory.generatePrivate(keySpec);
// 对数据解密
Cipher cipher = Cipher.getInstance(factory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, privateKey);
result = cipher.doFinal(data);
} catch (Exception e) {
e.printStackTrace();
}
return result;
} /**
* 私钥解密
* @param source
* @param privateKey
* @return
*/
public static String decryptByPublicKey(String source,String privateKey) throws Exception{
byte[] word=decryptBase64(source);
String decWord = new String(decryptByPrivateKey(word, privateKey));
return decWord;
} /**
* 私钥解密
* @param data 加密数据
* @param key 公钥
* @return
*/
public static byte[] decryptByPublicKey(byte[] data, String key) {
byte[] result = null;
try {
// 对公钥解密
byte[] bytes = decryptBase64(key);
// 取得公钥
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
KeyFactory factory = KeyFactory.getInstance(KEY_RSA);
PublicKey publicKey = factory.generatePublic(keySpec);
// 对数据解密
Cipher cipher = Cipher.getInstance(factory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, publicKey);
result = cipher.doFinal(data);
} catch (Exception e) {
e.printStackTrace();
}
return result;
} /**
* 公钥加密
* @param data 待加密数据
* @param key 公钥
* @return
*/
public static byte[] encryptByPublicKey(byte[] data, String key) {
byte[] result = null;
try {
byte[] bytes = decryptBase64(key);
// 取得公钥
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
KeyFactory factory = KeyFactory.getInstance(KEY_RSA);
PublicKey publicKey = factory.generatePublic(keySpec);
// 对数据加密
Cipher cipher = Cipher.getInstance(factory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
result = cipher.doFinal(data);
} catch (Exception e) {
e.printStackTrace();
}
return result;
} /**
* 私钥加密
* @param data 待加密数据
* @param key 私钥
* @return
*/
public static byte[] encryptByPrivateKey(byte[] data, String key) {
byte[] result = null;
try {
byte[] bytes = decryptBase64(key);
// 取得私钥
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes);
KeyFactory factory = KeyFactory.getInstance(KEY_RSA);
PrivateKey privateKey = factory.generatePrivate(keySpec);
// 对数据加密
Cipher cipher = Cipher.getInstance(factory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
result = cipher.doFinal(data);
} catch (Exception e) {
e.printStackTrace();
}
return result;
} /**
* 获取公钥
* @param map
* @return
*/
public static String getPublicKey(Map<String, Object> map) {
String str = "";
try {
Key key = (Key) map.get(KEY_RSA_PUBLICKEY);
str = encryptBase64(key.getEncoded());
} catch (Exception e) {
e.printStackTrace();
}
return str;
} /**
* 获取私钥
* @param map
* @return
*/
public static String getPrivateKey(Map<String, Object> map) {
String str = "";
try {
Key key = (Key) map.get(KEY_RSA_PRIVATEKEY);
str = encryptBase64(key.getEncoded());
} catch (Exception e) {
e.printStackTrace();
}
return str;
} /**
* BASE64 解密
* @param key 需要解密的字符串
* @return 字节数组
* @throws Exception
*/
public static byte[] decryptBase64(String key) throws Exception {
return (new BASE64Decoder()).decodeBuffer(key);
} /**
* BASE64 加密
* @param key 需要加密的字节数组
* @return 字符串
* @throws Exception
*/
public static String encryptBase64(byte[] key) throws Exception {
return (new BASE64Encoder()).encodeBuffer(key);
} public static String privateKey= "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKcsdtVapeDOkxJX\n" +
"D8QxweV+R9Vt1mDMs44vS4zDa3cr/DVEvvecHAjc6jdpgwQ6k+H5Dx54JlHOk463\n" +
"3YLI9Iy+1+opy13GXeQ2vdV95B7UQKxPhzcf092H0uA4RKelTYaYCghNLH7xflPB\n" +
"lFM1le7KrLHEc4xngpUWx9Us8ETVAgMBAAECgYAxVJqgbMZkJzEZCV3arEAmQ3RZ\n" +
"E7deCym0/FnT6NquaOlcorOjh4pyRxZKUbVaqxp2ZTND73qHS2kZhUI1VK1s3M9y\n" +
"i7HuOKncuDp4W96CwI6owoDlAiGcvDXAuptMauXzvh3Woww7VrJ0xvSHwOMCPFxj\n" +
"DN2nqDD7a+jjNVANZQJBAM1CjzizQn/M69ERkSSlbvJIXYNjdj1oYBOVINt2+Jjn\n" +
"kZDuF7vqX+ycKB7XZDmX4rLvbLB8wI73vdaID+KlsGsCQQDQf7Goo5dXxiCE0XhG\n" +
"W0/ARmsH5fefBQHRdAWmHMOoF8SapYiWnweyDyUrnBT4b0QVHC1hJ+Mh9lkBobM7\n" +
"Si+/AkEAxOD72SnwNf9Ljaxo6JqZsWEB+T2Us1ADH6Vh77/MsXUkZbxKHZ+wRJZ/\n" +
"0R1OcAOkmXcXbK0sUbWFbFnzyrScYwJAL8jUQr4bdXZnBYmscxOCV6LL7Od7tOpE\n" +
"3Ggm00dMYD3yRS8i+sI/1UM7VZ9T/wwhImVu0RF/MM1w4LrahQAfqQJBAJo5L4IV\n" +
"mQdbs6D3wflp4/lI4DTCM7fBISrT2j3nR/RMhTd4pcY62qADbGWjE6jEZWk/yQZV\n" +
"ug8HHCCjeRVf6U4=\n";
public static String publicKey= "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCnLHbVWqXgzpMSVw/EMcHlfkfV\n" +
"bdZgzLOOL0uMw2t3K/w1RL73nBwI3Oo3aYMEOpPh+Q8eeCZRzpOOt92CyPSMvtfq\n" +
"Kctdxl3kNr3VfeQe1ECsT4c3H9Pdh9LgOESnpU2GmAoITSx+8X5TwZRTNZXuyqyx\n" +
"xHOMZ4KVFsfVLPBE1QIDAQAB\n"; }
AES加密:
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec; import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder; public class AesEncodeUtil { //初始向量
public static final String VIPARA = "0102030405060708"; //AES 为16bytes. DES 为8bytes //编码方式
public static final String bm = "UTF-8"; //私钥
private static final String ASE_KEY="abc"; //AES固定格式为128/192/256 bits.即:16/24/32bytes。DES固定格式为128bits,即8bytes。 /**
* 加密
*
* @param cleartext
* @return
*/
public static String encrypt(String cleartext) {
//加密方式: AES128(CBC/PKCS5Padding) + Base64, 私钥:aabbccddeeffgghh
try {
IvParameterSpec zeroIv = new IvParameterSpec(VIPARA.getBytes());
//两个参数,第一个为私钥字节数组, 第二个为加密方式 AES或者DES
SecretKeySpec key = new SecretKeySpec(ASE_KEY.getBytes(), "AES");
//实例化加密类,参数为加密方式,要写全
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); //PKCS5Padding比PKCS7Padding效率高,PKCS7Padding可支持IOS加解密
//初始化,此方法可以采用三种方式,按加密算法要求来添加。(1)无第三个参数(2)第三个参数为SecureRandom random = new SecureRandom();中random对象,随机数。(AES不可采用这种方法)(3)采用此代码中的IVParameterSpec
cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
//加密操作,返回加密后的字节数组,然后需要编码。主要编解码方式有Base64, HEX, UUE,7bit等等。此处看服务器需要什么编码方式
byte[] encryptedData = cipher.doFinal(cleartext.getBytes(bm)); return new BASE64Encoder().encode(encryptedData);
} catch (Exception e) {
e.printStackTrace();
return "";
}
} /**
* 解密
*
* @param encrypted
* @return
*/
public static String decrypt(String encrypted) {
try {
byte[] byteMi = new BASE64Decoder().decodeBuffer(encrypted);
IvParameterSpec zeroIv = new IvParameterSpec(VIPARA.getBytes());
SecretKeySpec key = new SecretKeySpec(
ASE_KEY.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
//与加密时不同MODE:Cipher.DECRYPT_MODE
cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);
byte[] decryptedData = cipher.doFinal(byteMi);
return new String(decryptedData, bm);
} catch (Exception e) {
e.printStackTrace();
return "";
}
} /**
* 测试
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception { String content = "test";
// 加密
System.out.println("加密前:" + content);
String encryptResult = encrypt(content); System.out.println("加密后:" + new String(encryptResult));
// 解密
String decryptResult = decrypt(encryptResult);
System.out.println("解密后:" + new String(decryptResult)); }
}
JAVA RSA加密AES加密的更多相关文章
- Java实现RSA加密&AES加密&DES加密
RSA package com.demo; import org.springframework.util.StringUtils; import javax.crypto.Cipher; impor ...
- java使用RSA与AES加密解密
首先了解下,什么是堆成加密,什么是非对称加密? 对称加密:加密与解密的密钥是相同的,加解密速度很快,比如AES 非对称加密:加密与解密的秘钥是不同的,速度较慢,比如RSA 先看代码(先会用在研究) 相 ...
- c# .NET RSA结合AES加密服务端和客户端请求数据
这几天空闲时间就想研究一下加密,环境是web程序,通过js请求后台返回数据,我想做的事js在发送请求前将数据加密,服务端收到后解密,待服务端处理完请求后,将处理结果加密返回给客户端,客户端在解密,于是 ...
- JavaScript前端和Java后端的AES加密和解密(转)
在实际开发项目中,有些数据在前后端的传输过程中需要进行加密,那就需要保证前端和后端的加解密需要统一.这里给大家简单演示AES在JavaScript前端和Java后端是如何实现加密和解密的. java端 ...
- 【5】JMicro其于RSA及AES加密实现安全服务调用
JMicro是基于Java实现的微服务平台,最近花了两个周未实现服务间安全调用支持. JMicro服务调用分两个部份,分别为内部服务间相互调用和外部客户端通过API网关调用JMicro集群内部服务,前 ...
- JavaScript前端和Java后端的AES加密和解密
在实际开发项目中,有些数据在前后端的传输过程中需要进行加密,那就需要保证前端和后端的加解密需要统一.这里给大家简单演示AES在JavaScript前端和Java后端是如何实现加密和解密的. 直接上代码 ...
- java.. C# 使用AES加密互解 采用AES-128-ECB加密模式
java需要下载外部包, commons codec.jar 1.6 較新的JAVA版本把Base64的方法改成靜態方法,可能會寫成Base64.encodeToString(encrypted, ...
- JAVA中使用AES加密解密
技术交流群: 233513714 /** * AES加密测试 * * @param str 加密参数 */ public void aesTest(String str) { log.info(&qu ...
- PHP对称加密-AES加密、DES加密
对称加密 对称加密算法是指,数据发信方将明文(原始数据)和密钥一起经过加密处理后,使其变成复杂的加密密文发送出去.收信方收到密文后,若要解读原文,则需要使用加密密钥及相关算法的逆算法对密文进行解密,使 ...
随机推荐
- 记一次git翻车事件
昨天dmp上线了 本来整个流程是 1.在本地1.4分支开发,开发完成push到origin/1.4,在远程仓库把1.4 merge到master分支 2.本地online分支先pull一下远程onli ...
- php 积分抽奖活动(大转盘)
以下是项目代码(公众号,使用积分进行抽奖活动),只可做参考: public function Sncode(){ $tid = I('request.tid', 0, 'intval'); // 大转 ...
- Eclipse使用相关配置
问题描述:The word is not correctly spelled问题分析:eclipse校验单词拼写造成,出现在配置文件中,会影响到程序的正常执行解决方案:在eclipse下的Window ...
- 创建表结构的sql语句
1.创建表结构 表名: ODS_PSP_DIS_DAY_CALC create table ODS_PSP_DIS_DAY_CALC ( ID CHAR(32) NOT NULL, DIS ...
- Swift.Operator-and-Items-in-Swift(1)
Operator and Item 1. ..< a for-in loop and the half-open range operator (..<) // Check each pa ...
- log4j.properties配置与将异常输出到Log日志文件实例
将异常输出到 log日志文件 实际项目中的使用: <dependencies> <dependency> <groupId>org.slf4j</groupI ...
- 3,fiddler手机端的设置
1,首先设置手机端代理 选择链接的无限网,设置其代理 2,安装手机证书 只有在启动fiddler的时候手机才能够上网, 在浏览器,输入主机ip+fiddler端口的地址 进入后是下边的界面 点击下载证 ...
- git 一些实用的api
v3 获取原始文件内容: curl -H "PRIVATE-TOKEN: <token>" -H "Content-Type: application/jso ...
- Maximum Sum Circular Subarray LT918
Given a circular array C of integers represented by A, find the maximum possible sum of a non-empty ...
- Reveal Cards In Increasing Order LT950
In a deck of cards, every card has a unique integer. You can order the deck in any order you want. ...