RSA加密解密操作
内部邀请码:C8E245J (不写邀请码,没有现金送)
国内私募机构九鼎控股打造,九鼎投资是在全国股份转让系统挂牌的公众公司,股票代码为430719,为“中国PE第一股”,市值超1000亿元。
原文地址: http://wlh.iteye.com/blog/134796
生成RSA密钥、保存到文件、从文件读取、加密、解密等操作。
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.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.bouncycastle.jce.provider.BouncyCastleProvider; public class RSATest { public static void main(String[] args) {
try {
RSATest encrypt = new RSATest();
String encryptText = "encryptText"; // Generate keys
KeyPair keyPair = encrypt.generateKey();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); byte[] e = encrypt.encrypt(publicKey, encryptText.getBytes());
byte[] de = encrypt.decrypt(privateKey, e);
System.out.println(toHexString(e));
System.out.println(toHexString(de));
} catch (Exception e) {
e.printStackTrace();
}
} public KeyPair generateKey() throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
keyPairGen.initialize(1024, new SecureRandom()); KeyPair keyPair = keyPairGen.generateKeyPair();
return keyPair;
} public void saveKey(KeyPair keyPair, String publicKeyFile,
String privateKeyFile) throws ConfigurationException {
PublicKey pubkey = keyPair.getPublic();
PrivateKey prikey = keyPair.getPrivate(); // save public key
PropertiesConfiguration publicConfig = new PropertiesConfiguration(
publicKeyFile);
publicConfig.setProperty("PULIICKEY", toHexString(pubkey.getEncoded()));
publicConfig.save(); // save private key
PropertiesConfiguration privateConfig = new PropertiesConfiguration(
privateKeyFile);
privateConfig.setProperty("PRIVATEKEY",
toHexString(prikey.getEncoded()));
privateConfig.save();
} /**
* @param filename
* @param type:
* 1-public 0-private
* @return
* @throws ConfigurationException
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public Key loadKey(String filename, int type)
throws ConfigurationException, NoSuchAlgorithmException,
InvalidKeySpecException {
PropertiesConfiguration config = new PropertiesConfiguration(filename);
KeyFactory keyFactory = KeyFactory.getInstance("RSA",
new BouncyCastleProvider()); if (type == 0) {
// privateKey
String privateKeyValue = config.getString("PULIICKEY");
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(
toBytes(privateKeyValue));
PrivateKey privateKey = keyFactory.generatePrivate(priPKCS8);
return privateKey; } else {
// publicKey
String privateKeyValue = config.getString("PRIVATEKEY");
X509EncodedKeySpec bobPubKeySpec = new X509EncodedKeySpec(
toBytes(privateKeyValue));
PublicKey publicKey = keyFactory.generatePublic(bobPubKeySpec);
return publicKey;
}
} /**
* Encrypt String.
*
* @return byte[]
*/
protected byte[] encrypt(RSAPublicKey publicKey, byte[] data) {
if (publicKey != null) {
try {
Cipher cipher = Cipher.getInstance("RSA",
new BouncyCastleProvider());
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(data);
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
} /**
* Basic decrypt method
*
* @return byte[]
*/
protected byte[] decrypt(RSAPrivateKey privateKey, byte[] raw) {
if (privateKey != null) {
try {
Cipher cipher = Cipher.getInstance("RSA",
new BouncyCastleProvider());
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(raw);
} catch (Exception e) {
e.printStackTrace();
}
} return null;
} public static String toHexString(byte[] b) {
StringBuilder sb = new StringBuilder(b.length * 2);
for (int i = 0; i < b.length; i++) {
sb.append(HEXCHAR[(b[i] & 0xf0) >>> 4]);
sb.append(HEXCHAR[b[i] & 0x0f]);
}
return sb.toString();
} public static final byte[] toBytes(String s) {
byte[] bytes;
bytes = new byte[s.length() / 2];
for (int i = 0; i < bytes.length; i++) {
bytes[i] = (byte) Integer.parseInt(s.substring(2 * i, 2 * i + 2),
16);
}
return bytes;
} private static char[] HEXCHAR = { '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; }
RSA加密解密操作的更多相关文章
- RSA加密解密与加签验签
RSA公钥加密算法是1977年由罗纳德·李维斯特(Ron Rivest).阿迪·萨莫尔(Adi Shamir)和伦纳德·阿德曼(Leonard Adleman)一起提出的.1987年7月首次在美国公布 ...
- C#的RSA加密解密签名,就为了支持PEM PKCS#8格式密钥对的导入导出
差点造了一整个轮子 .Net Framework 4.5 里面的RSA功能,并未提供简单对PEM密钥格式的支持(.Net Core有咩?),差点(还远着)造了一整个轮子,就为了支持PEM PKCS#8 ...
- 微信小程序(17)-- RSA加密 解密 加签 验签
RSA加密 解密 加签 验签 /** * 注:区分RSA私钥的类型,有pkcs1和pkcs8.pkcs8格式的私钥主要用于Java中 pkcs1格式: -----BEGIN RSA PRIVATE K ...
- 最通俗易懂的RSA加密解密指导
前言 RSA加密算法是一种非对称加密算法,简单来说,就是加密时使用一个钥匙,解密时使用另一个钥匙. 因为加密的钥匙是公开的,所又称公钥,解密的钥匙是不公开的,所以称为私钥. 密钥 关于RSA加密有很多 ...
- .net Xml加密解密操作
生成密钥的方法: /// <summary>生成RSA加密 解密的 密钥 /// 生成的key就是 方法EncryptByRSA与DecryptByRSA用的key了 /// </s ...
- 兼容javascript和C#的RSA加密解密算法,对web提交的数据进行加密传输
Web应用中往往涉及到敏感的数据,由于HTTP协议以明文的形式与服务器进行交互,因此可以通过截获请求的数据包进行分析来盗取有用的信息.虽然https可以对传输的数据进行加密,但是必须要申请证书(一般都 ...
- iOS使用Security.framework进行RSA 加密解密签名和验证签名
iOS 上 Security.framework为我们提供了安全方面相关的api: Security框架提供的RSA在iOS上使用的一些小结 支持的RSA keySize 大小有:512,768,10 ...
- openssl evp RSA 加密解密
openssl evp RSA 加密解密 可以直接使用RSA.h 提供的接口 如下测试使用EVP提供的RSA接口 1. EVP提供的RSA 加密解密 主要接口: int EVP_PKEY_encryp ...
- C# 与JAVA 的RSA 加密解密交互,互通,C#使用BouncyCastle来实现私钥加密,公钥解密的方法
因为C#的RSA加密解密只有公钥加密,私钥解密,没有私钥加密,公钥解密.在网上查了很久也没有很好的实现.BouncyCastle的文档少之又少.很多人可能会说,C#也是可以的,通过Biginteger ...
随机推荐
- codeforces 390E Inna and Large Sweet Matrix
本题的主要算法就是区间更新和区间求和: 可以用线段树和树状数组来做: 感觉线段树写的太麻烦了,看到官方题解上说可以用树状数组做,觉得很神奇,以前用过的树状数组都是单点维护,区间求和的: 其实树状数组还 ...
- MAC下《暗黑世界》客户端版本编译说明!!
原地址:http://blog.csdn.net/uxqclm/article/details/11970659 2013-09-24 12:02 161人阅读 评论(0) 收藏 举报 目录(?) ...
- MySql从服务器延迟解决方案
在从服务器上执行show slave status;可以查看到很多同步的参数,我们需要特别注意的参数如下:Master_Log_File: SLAVE中的I/ ...
- FLV封装格式及分析器工具
http://blog.csdn.net/leixiaohua1020/article/details/17934487 FLV封装原理 FLV格式的封装原理,贴上来辅助学习之用. FLV(F ...
- java的几种for循环方法
自从jdk升级为1.8以后,for循环又升级了 classic for classic foreach List.forEach() List.stream().forEach() List.para ...
- Sublime Text 插件 autoprefixer
Sublime Text 早就有插件(Sublime Prefixr)使用 prefixr 的 API 来自动完成 CSS 前缀,但是 autoprefixer 更牛,这款可使用 Can I Use ...
- jquery ajax cache的问题
function test() { $.ajax({ type:'GET', url:"tt. ...
- Innodb加载数据字典 && flush tables
测试了两个case,属于之前blog的遗留问题: innodb如何加载数据字典 flush tables都做了什么操作 先来看下innodb加载数据字典: 首次使用:select * from tt; ...
- Arch linux安装
安装archlinux可参考: http://blog.sina.com.cn/s/blog_69e5d8400101bqlj.html http://www.cnblogs.com/mad/p/32 ...
- [ECNU 1624] 求交集多边形面积
求交集多边形面积 Time Limit:1000MS Memory Limit:30000KB Total Submit:98 Accepted:42 Description 在平面上有两给定的凸多边 ...