JDK自带方法实现RSA非对称加密
package jdbc.pro.lin; import java.security.InvalidKeyException;
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.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map; import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException; import org.apache.commons.codec.binary.Base64; public class MyRSA {
public static final String KEY_ALGORITHM = "RSA";
/** 貌似默认是RSA/NONE/PKCS1Padding,未验证 */
public static final String CIPHER_ALGORITHM = "RSA/ECB/PKCS1Padding";
public static final String PUBLIC_KEY = "publicKey";
public static final String PRIVATE_KEY = "privateKey"; /** RSA密钥长度必须是64的倍数,在512~65536之间。默认是1024 */
public static final int KEY_SIZE = 2048; public static final String PLAIN_TEXT = "MANUTD is the greatest club in the world"; public static void main(String[] args) {
Map<String, byte[]> keyMap = generateKeyBytes(); // 加密
PublicKey publicKey = restorePublicKey(keyMap.get(PUBLIC_KEY)); byte[] encodedText = RSAEncode(publicKey, PLAIN_TEXT.getBytes());
System.out.println("RSA encoded: " + Base64.encodeBase64String(encodedText)); // 解密
PrivateKey privateKey = restorePrivateKey(keyMap.get(PRIVATE_KEY));
System.out.println("RSA decoded: "
+ RSADecode(privateKey, encodedText));
} /**
* 生成密钥对。注意这里是生成密钥对KeyPair,再由密钥对获取公私钥
*
* @return
*/
public static Map<String, byte[]> generateKeyBytes() { try {
KeyPairGenerator keyPairGenerator = KeyPairGenerator
.getInstance(KEY_ALGORITHM);
keyPairGenerator.initialize(KEY_SIZE);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); Map<String, byte[]> keyMap = new HashMap<String, byte[]>();
keyMap.put(PUBLIC_KEY, publicKey.getEncoded());
keyMap.put(PRIVATE_KEY, privateKey.getEncoded());
return keyMap;
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
} /**
* 还原公钥,X509EncodedKeySpec 用于构建公钥的规范
*
* @param keyBytes
* @return
*/
public static PublicKey restorePublicKey(byte[] keyBytes) {
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
e.printStackTrace();
}
return null;
} /**
* 还原私钥,PKCS8EncodedKeySpec 用于构建私钥的规范
*
* @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
e.printStackTrace();
}
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
e.printStackTrace();
}
return null; } /**
* 解密,三步走。
*
* @param key
* @param encodedText
* @return
*/
public static String RSADecode(PrivateKey key, byte[] encodedText) { try {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key);
return new String(cipher.doFinal(encodedText));
} catch (NoSuchAlgorithmException | NoSuchPaddingException
| InvalidKeyException | IllegalBlockSizeException
| BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null; }
}
几点注意:
1.用到了KeyFactory。
2.用到了公私钥的规范。
3.RSA密钥长度从512~65536,必须是64的整数倍


JDK自带方法实现RSA非对称加密的更多相关文章
- JDK自带方法实现AES对称加密
请看代码. 1 package jdbc.pro.lin; 2 3 import java.security.InvalidAlgorithmParameterException; 4 import ...
- JDK自带方法实现RSA数字签名
JDK 6只支持MD2withRSA, MD5withRSA, SHA1withRSA 其他的如SHA512withRSA需要第三方包支持,如BC(bouncy castle) --20151126 ...
- SSH公钥登录和RSA非对称加密
SSH登录方式 接触过Linux服务器的同学肯定用过SSH协议登录系统,通常SSH协议都有两种登录方式:密码口令登录和公钥登陆. 一.密码口令(类似于账号密码登录) 1.客户端连接服务器,服务器把公钥 ...
- Atitit RSA非对称加密原理与解决方案
Atitit RSA非对称加密原理与解决方案 1.1. 一.一点历史 1 1.2. 八.加密和解密 2 1.3. 二.基于RSA的消息传递机制 3 1.4. 基于rsa的授权验证机器码 4 1.5. ...
- RSA非对称加密Java实现
原文 加密基础方法类 import java.security.MessageDigest; import sun.misc.BASE64Decoder; import sun.misc.BASE64 ...
- 前端js,后台python实现RSA非对称加密
先熟悉使用 在后台使用RSA实现秘钥生产,加密,解密; # -*- encoding:utf-8 -*- import base64 from Crypto import Random from Cr ...
- 前后端数据加密传输 RSA非对称加密
任务需求:要求登陆时将密码加密之后再进行传输到后端. 经过半天查询摸索折腾,于是有了如下成果: 加密方式:RSA非对称加密.实现方式:公钥加密,私钥解密.研究进度:javascript与java端皆已 ...
- JSON 接口如何实现 RSA 非对称加密与签名
代码地址如下:http://www.demodashi.com/demo/14000.html 一.概述 1. 数字签名的作用:保证数据完整性,机密性和发送方角色的不可抵赖性,加密与签字结合时,两套公 ...
- javascript版前端页面RSA非对称加密解密
最近由于项目需要做一个url传参,并在页面显示参数内容的需求,这样就会遇到一个url地址可能会被假冒, 并传递非法内容显示在页面的尴尬情况 比如xxx.shtml?server=xxx是坏人& ...
随机推荐
- Windows.document对象
一.找到元素: docunment.getElementById("id"):根据id找,最多找一个:var a =docunment.getElementById("i ...
- Makefile第四讲:include 引用其它makefile文件
main.cpp #include "classes/fun.h" int main() { Test::display("Hello makefile"); ...
- 前端模块化开发篇之grunt&webpack篇
几个月前写了一篇有关gulp和browserify来做前端构建的博客,因为browserify用来做js的打包时可能有些麻烦(特别是在写React的时候),所以这里再强烈推荐一款js打包工具-webp ...
- ShadowGun Deadzone 放出 GM Kit Mod 包
一向在技术上比较开放的 MadFinger 继上次给出 shadowgun 的关卡包之后,这次更加大方的给出了更加完整的关卡的代码,甚至包括服务器:ShadowGun Deadzone GM Kit. ...
- 蔡勒(Zeller)公式
蔡勒(Zeller)公式,是一个计算星期的公式,随便给一个日期,就能用这个公式推算出是星期几. W =[ [c/4] - 2c + y + [y/4] + [13 * (m+1) / 5] + d - ...
- yum puppet 并整合控制台
上篇说了下在ubuntu12.04上安装puppet,安装的版本为puppet2.7.11版本,今天尝试了下在CentOS6.4系统上安装puppet 3.1.1版本,本文参考chenshake的文章 ...
- 使用GSoap开发WebService客户端与服务端
Gsoap 编译工具提供了一个SOAP/XML 关于C/C++ 语言的实现, 从而让C/C++语言开发web服务或客户端程序的工作变得轻松了很多. 用gsoap开发web service的大致思路 我 ...
- oracle10g前期准备
上午在虚拟机安装了oracle10g,安装比较简单,只是前期工作比较多,如: 在Root用户下执行以下步骤: 1)修改用户的SHELL的限制,修改/etc/security/limits.conf文件 ...
- linux内核--几个上下文(context)
为了控制进程的执行,内核必须有能力挂起正在CPU上运行的进程,并恢复以前挂起的某个进程的执行,这种行为叫进程切换(process switch),任务切换(task switch)或上下文切换(con ...
- hdu1698(线段树的区间替换)
HDU1698 #include <bits/stdc++.h> using namespace std; #define Maxn 1001000*4 struct Node{ int ...