国内私募机构九鼎控股打造APP,来就送 20元现金领取地址:http://jdb.jiudingcapital.com/phone.html
内部邀请码: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加密解密操作的更多相关文章

  1. RSA加密解密与加签验签

    RSA公钥加密算法是1977年由罗纳德·李维斯特(Ron Rivest).阿迪·萨莫尔(Adi Shamir)和伦纳德·阿德曼(Leonard Adleman)一起提出的.1987年7月首次在美国公布 ...

  2. C#的RSA加密解密签名,就为了支持PEM PKCS#8格式密钥对的导入导出

    差点造了一整个轮子 .Net Framework 4.5 里面的RSA功能,并未提供简单对PEM密钥格式的支持(.Net Core有咩?),差点(还远着)造了一整个轮子,就为了支持PEM PKCS#8 ...

  3. 微信小程序(17)-- RSA加密 解密 加签 验签

    RSA加密 解密 加签 验签 /** * 注:区分RSA私钥的类型,有pkcs1和pkcs8.pkcs8格式的私钥主要用于Java中 pkcs1格式: -----BEGIN RSA PRIVATE K ...

  4. 最通俗易懂的RSA加密解密指导

    前言 RSA加密算法是一种非对称加密算法,简单来说,就是加密时使用一个钥匙,解密时使用另一个钥匙. 因为加密的钥匙是公开的,所又称公钥,解密的钥匙是不公开的,所以称为私钥. 密钥 关于RSA加密有很多 ...

  5. .net Xml加密解密操作

    生成密钥的方法: /// <summary>生成RSA加密 解密的 密钥 /// 生成的key就是 方法EncryptByRSA与DecryptByRSA用的key了 /// </s ...

  6. 兼容javascript和C#的RSA加密解密算法,对web提交的数据进行加密传输

    Web应用中往往涉及到敏感的数据,由于HTTP协议以明文的形式与服务器进行交互,因此可以通过截获请求的数据包进行分析来盗取有用的信息.虽然https可以对传输的数据进行加密,但是必须要申请证书(一般都 ...

  7. iOS使用Security.framework进行RSA 加密解密签名和验证签名

    iOS 上 Security.framework为我们提供了安全方面相关的api: Security框架提供的RSA在iOS上使用的一些小结 支持的RSA keySize 大小有:512,768,10 ...

  8. openssl evp RSA 加密解密

    openssl evp RSA 加密解密 可以直接使用RSA.h 提供的接口 如下测试使用EVP提供的RSA接口 1. EVP提供的RSA 加密解密 主要接口: int EVP_PKEY_encryp ...

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

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

随机推荐

  1. 《暗黑世界》安卓APK 编译流程详细说明教程!(图文)

    原地址:http://bbs.gameres.com/forum.php?mod=viewthread&tid=223671 关于开发环境的搭建,之前的相关文档已经很详细的说明,对环境的搭建请 ...

  2. phpexcelreader超级简单使用

    phpexcelreader超级简单使用 该php类可以到官网下载:http://www.codeplex.com/PHPExcel,下载的文件不能直接使用要看下面的备注. 备注: 1.要将olere ...

  3. live555

    相关资料: Live555 是一个为流媒体提供解决方案的跨平台的C++开源项目,它实现了对标准流媒体传输协议如RTP/RTCP.RTSP.SIP等的支持.Live555实现 了对多种音视频编码格式的音 ...

  4. ANDROID_MARS学习笔记_S01原始版_009_SQLite

    一.代码1.xml(1)activity_main.xml <?xml version="1.0" encoding="utf-8"?> <L ...

  5. java.sizeOf

    Introduction With java.SizeOf you can measure the real memory size of your Java objects. Download it ...

  6. 【Lucene3.6.2入门系列】第03节_简述Lucene中常见的搜索功能

    package com.jadyer.lucene; import java.io.File; import java.io.IOException; import java.text.SimpleD ...

  7. 【HTML5】Canvas之globalCompositeOperation属性详解

    globalCompositeOperation即Canvas中的合成操作. 1.source-over 这是默认值,他表示绘制的图形将画在现有画布之上 <!DOCTYPE html> & ...

  8. codeforces 652E Pursuit For Artifacts 边双连通分量

    题意:n个点,m条边的无向图,有的边上有标记,每条边只能走一次 给你一个起点,一个终点,询问是否能找到从起点到终点的路径,这条路径至少包含一条含有标记的边 分析:然后边双缩点 下面介绍一下边双的性质 ...

  9. POJ 3013

    思路:ans = 每条边(u,v)*v的子树节点的w = 所有的dist[v]*w[v]之和; #include<iostream> #include<queue> #incl ...

  10. Code First to an Existing Database

    Code First to an Existing Database https://msdn.microsoft.com/en-us/data/jj200620 https://weblogs.as ...