RSA.java


package org.icesnow.jeasywx.util.security; import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
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; import javax.crypto.Cipher; import org.apache.log4j.Logger; import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder; /**
* @author: 782987839@qq.com
* @date:2016-3-23下午12:25:07
* @version: 1.0
* @describe: JAVA实现RSA加密,非对称加密算法
*
*/
public class RSA {
private static Logger logger = Logger.getLogger(RSA.class); public static final String KEY_ALGORITHM = "RSA";
public static final String SIGNATURE_ALGORITHM = "MD5withRSA"; private static final String PUBLIC_KEY = "RSAPublicKey";
private static final String PRIVATE_KEY = "RSAPrivateKey"; /**
* 初始化密钥
*
* @return
* @throws Exception
*/
public static Map<String, Object> initKey() throws Exception {
KeyPairGenerator keyPairGen = KeyPairGenerator
.getInstance(KEY_ALGORITHM);
keyPairGen.initialize(1024);
KeyPair keyPair = keyPairGen.generateKeyPair(); // 公钥
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
// logger.info("------" + publicKey);
// 私钥
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
// logger.info("------" + publicKey); Map<String, Object> keyMap = new HashMap<String, Object>(2); keyMap.put(PUBLIC_KEY, publicKey);
keyMap.put(PRIVATE_KEY, privateKey);
return keyMap;
} /**
* 取得私钥
*
* @param keyMap
* @return
* @throws Exception
*/
public static String getPrivateKey(Map<String, Object> keyMap)
throws Exception {
Key key = (Key) keyMap.get(PRIVATE_KEY);
return encryptBASE64(key.getEncoded());
} /**
* 取得公钥
*
* @param keyMap
* @return
* @throws Exception
*/
public static String getPublicKey(Map<String, Object> keyMap)
throws Exception {
Key key = (Key) keyMap.get(PUBLIC_KEY);
return encryptBASE64(key.getEncoded());
} /**
* 解密<br>
* 用私钥解密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] decryptByPrivateKey(byte[] data, String key)
throws Exception {
// 对密钥解密
byte[] keyBytes = decryptBASE64(key); // 取得私钥
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec); // 对数据解密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, privateKey); return cipher.doFinal(data);
} /**
* 解密<br>
* 用公钥解密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] decryptByPublicKey(byte[] data, String key)
throws Exception {
// 对密钥解密
byte[] keyBytes = decryptBASE64(key); // 取得公钥
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key publicKey = keyFactory.generatePublic(x509KeySpec); // 对数据解密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, publicKey); return cipher.doFinal(data);
} /**
* 加密<br>
* 用公钥加密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] encryptByPublicKey(byte[] data, String key)
throws Exception {
// 对公钥解密
byte[] keyBytes = decryptBASE64(key); // 取得公钥
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key publicKey = keyFactory.generatePublic(x509KeySpec); // 对数据加密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, publicKey); return cipher.doFinal(data);
} /**
* 加密<br>
* 用私钥加密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] encryptByPrivateKey(byte[] data, String key)
throws Exception {
// 对密钥解密
byte[] keyBytes = decryptBASE64(key); // 取得私钥
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec); // 对数据加密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, privateKey); return cipher.doFinal(data);
} /**
* 用私钥对信息生成数字签名
*
* @param data
* 加密数据
* @param privateKey
* 私钥
*
* @return
* @throws Exception
*/
public static String sign(byte[] data, String privateKey) throws Exception {
// 解密由base64编码的私钥
byte[] keyBytes = decryptBASE64(privateKey); // 构造PKCS8EncodedKeySpec对象
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); // KEY_ALGORITHM 指定的加密算法
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); // 取私钥匙对象
PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec); // 用私钥对信息生成数字签名
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initSign(priKey);
signature.update(data); return encryptBASE64(signature.sign());
} /**
* 校验数字签名
*
* @param data
* 加密数据
* @param publicKey
* 公钥
* @param sign
* 数字签名
*
* @return 校验成功返回true 失败返回false
* @throws Exception
*
*/
public static boolean verify(byte[] data, String publicKey, String sign)
throws Exception { // 解密由base64编码的公钥
byte[] keyBytes = decryptBASE64(publicKey); // 构造X509EncodedKeySpec对象
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes); // KEY_ALGORITHM 指定的加密算法
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); // 取公钥匙对象
PublicKey pubKey = keyFactory.generatePublic(keySpec); Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initVerify(pubKey);
signature.update(data); // 验证签名是否正常
return signature.verify(decryptBASE64(sign));
} private static byte[] decryptBASE64(String key) throws Exception {
return (new BASE64Decoder()).decodeBuffer(key);
} private static String encryptBASE64(byte[] key) throws Exception {
return (new BASE64Encoder()).encodeBuffer(key);
} public static void main(String[] args) {
Map<String, Object> keyMap;
try {
//取得公钥和么私钥
keyMap = initKey();
String publicKey = getPublicKey(keyMap);
logger.info("字符类型公钥:" + publicKey); String privateKey = getPrivateKey(keyMap);
logger.info("字符类型私钥:" + privateKey); System.err.println("公钥加密——私钥解密");
String source = "这是一行没有任何意义的文字,你看完了等于没看,不是吗?";
System.out.println("\r加密前文字:\r\n" + source);
byte[] data = source.getBytes();
byte[] encodedData = encryptByPublicKey(data, publicKey);
System.out.println("加密后文字:\r\n" + encryptBASE64(encodedData));
byte[] decodedData = decryptByPrivateKey(encodedData, privateKey);
String target = new String(decodedData);
System.out.println("解密后文字: \r\n" + target); System.err.println("私钥加密——公钥解密");
String source1 = "这是一行测试RSA数字签名的无意义文字";
System.out.println("原文字:\r\n" + source1);
byte[] data1 = source1.getBytes();
byte[] encodedData1 = encryptByPrivateKey(data1, privateKey);
System.out.println("加密后:\r\n" + new String(encodedData1));
byte[] decodedData1 = decryptByPublicKey(encodedData1, publicKey);
String target1 = new String(decodedData1);
System.out.println("解密后: \r\n" + target1);
System.err.println("私钥签名——公钥验证签名");
String sign = sign(encodedData, privateKey);
System.err.println("签名:\r" + sign);
boolean status = verify(encodedData, publicKey, sign);
System.err.println("验证结果:\r" + status);
// //对内容进行加密和解密
String str = "this is test RSA";
byte[] strByte = str.getBytes();
// //私钥加密
byte[] encode = encryptByPrivateKey(strByte,privateKey);
logger.info("私钥加密结果:" + encryptBASE64(encode));
//公钥解密
byte[] decode = decryptByPublicKey(encode,publicKey);
logger.info("公钥解密结果:" + new String(decode)); } catch (Exception e) {
e.printStackTrace();
}
} }

JAVA实现RSA加密,非对称加密算法的更多相关文章

  1. JAVA实现RSA加密解密 非对称算法

    首先RSA是一个非对称的加密算法.所以在使用该算法加密解密之前,必须先行生成密钥对.包含公钥和私钥 JDK中提供了生成密钥对的类KeyPairGenerator,实比例如以下: public stat ...

  2. Java使用RSA加密解密及签名校验

    该工具类中用到了BASE64,需要借助第三方类库:javabase64-1.3.1.jar注意:RSA加密明文最大长度117字节,解密要求密文最大长度为128字节,所以在加密和解密的过程中需要分块进行 ...

  3. C# 与JAVA 的RSA 加密解密交互,互通,C#使用BouncyCastle来实现私钥加密,公钥解密的方法

    因为C#的RSA加密解密只有公钥加密,私钥解密,没有私钥加密,公钥解密.在网上查了很久也没有很好的实现.BouncyCastle的文档少之又少.很多人可能会说,C#也是可以的,通过Biginteger ...

  4. Java使用RSA加密解密签名及校验

    RSA加密解密类: 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 ...

  5. RSA典型非对称加密算法

    私钥加密-->公钥解密,反之亦然,但不安全.也可以当做数字签名. public class RSACoder {         //非对称加密算法         public static  ...

  6. Java采用RSA加密及解密技术的有关Maven项目的配置流程:

    第一步: 获得RSA公钥私钥(秘钥格式:PKCS#8 ,测试使用的是无私钥密码的) 公钥: -----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4G ...

  7. php与JAVA的RSA加密互通

    Java 版本RSA 进行加密解密 在网上查询了好几天,最终找到解决方案,网络上都是通过Cipher.getInstance("RSA"); 而改成Cipher.getInstan ...

  8. iOS and JAVA 的 RSA 加密解密 (转载整理 )

    参考原文地址:http://www.cnblogs.com/makemelike/articles/3802518.html (至于RSA的基本原理,大家可以看 阮一峰的网络日志 的 RSA算法原理( ...

  9. Java实现RSA加密&AES加密&DES加密

    RSA package com.demo; import org.springframework.util.StringUtils; import javax.crypto.Cipher; impor ...

随机推荐

  1. php-fpm 进程在云服务器cpu分配不均匀

    8核的云服务器,开了200个php-fpm进程,用top命令查看  大部分进程都在cpu 0 上跑着,导致其他cpu 负载很低,cpu分配不均匀: 使用shell 解决问题: 列出所有php-fpm ...

  2. code first关系表达

    1.一对多关系 [Table("classInfo")] public class ClassInfo { public int Id { get; set; } public s ...

  3. webpack.config.js====图片处理

    1. 安装依赖: cnpm install --save-dev url-loader image-webpack-loader html-loader 2. webpack.config.js规则的 ...

  4. canvas制作运动的小球

    <!DOCTYPE html> <head> <title>canvas</title> <style> .canvas{ border: ...

  5. Promise对象(异步编程)

    Promise对象解决函数的异步调用(跟回调函数一样) 三种状态: 未完成(pending)已完成(fulfilled)失败(rejected) 通过then函数来链式调用 目前市面上流行的一些类库:

  6. C++ Knowledge series 4

    Programming language evolves always along with Compiler's evolvement The Semantics of Function C++ s ...

  7. js 判断浏览器类型

    前言 工作中需要用到判断浏览器类型,网上找到的内容不怎么全,故在此进行一下总结. 一.不同浏览器及版本下User-Agent信息 待续.....欢迎补充 二.根据User-Agent信息进行判断 参考 ...

  8. 获取当前事件对象及this的用法

    js <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta h ...

  9. 为什么要使用TLSv1.2和System SSL?

    FTP 和 Telnet 正是核心联网应用程序的两个示例.为 System SSL 编程接口编码的供应商应用程序可以通过更改代码来利用这些新支持. 这是安全套接层 (SSL) 协议的最新版本,也是最为 ...

  10. Help for enable SSL 3.0 and disable TLS 1.0..

    https://support.mozilla.org/en-US/questions/967266 i cant find tab Encryption for enable SSL 3.0 and ...