国内私募机构九鼎控股打造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. [转载]MongoDB学习(三):MongoDB Shell的使用

    MongoDB shell MongoDB自带简洁但功能强大的JavaScript shell.JavaScript shell键入一个变量会将变量的值转换为字符串打印到控制台上. 下面介绍基本的操作 ...

  2. D-Bus,kdbus和Binder

    http://blog.sina.com.cn/s/blog_4af327e10101irie.html 材料来自:The unveiling of kdbus 和 Kdbus Details .后一 ...

  3. Android layout_gravity失效的问题

    相信对于Android的初学者来说,大家都曾经被layout里这两个极其相似的属性迷惑过.简单使用一下搜索工具,我们就不难找到下面这样的答案: layout_gravity 表示组件自身在父组件中的位 ...

  4. gdb查看虚函数表、函数地址

    1. 查看函数地址     看函数在代码的哪一行,使用info line就可以看到类似下面这中输出 点击(此处)折叠或打开 (gdb) info line a.cpp:10 Line 10 of &q ...

  5. [置顶] *p++/*++p区别-linux

    #include <stdio.h> main() { char * s = "123456"; char * p; p = s; printf( "%c\n ...

  6. 常用linux命令合集(持续更新中)

    我的博客:www.while0.com 开发调试 readelf-a 查看elf文件中的内容 hexdump -C 用16进制查看文件 objdump -d 反汇编目标文件 nm 查看目标文件或者可执 ...

  7. Android开发UI之android:gravity / android:layout_Gravity,android:padding / android:layout_margin属性区分

    android:gravity / android:layout_Gravity区别: android:gravity 是设置该view里面的内容相对于该view的位置,例如设置button里面的te ...

  8. poj3177

    边双连通有一个非常简单的做法就是先找出所有桥,然后再dfs一次不走桥即可答案是(叶子节点的个数+1)/2 type node=record next,po:longint; end; ..] of n ...

  9. c程序设计语言_习题1-9_将输入流复制到输出流,并将多个空格过滤成一个空格

    Write a program to copy its input to its output, replacing each string of one or more blanks by a si ...

  10. CDN原理

    要了解CDN的实现原理,首先让我们来回顾一下网站传统的访问过程,以便理解其与CDN访问方式之间的差别: 由上图可见,传统的网站访问过程为:1. 用户在浏览器中输入要访问的域名:2. 浏览器向域名解析服 ...