`
tomcat_oracle
  • 浏览: 310488 次
社区版块
存档分类
最新评论

Java进行RSA加解密的例子

    博客分类:
  • Java
阅读更多
加密是保证数据安全的手段之一。加密是将纯文本数据转换为难以理解的密文;解密是将密文转换回纯文本。
  数据的加解密属于密码学的范畴。通常,加密和解密都需要使用一些秘密信息,这些秘密信息叫做密钥,将纯文本转为密文或者转回的时候都要用到这些密钥。
  对称加密指的是发送者和接收者共用同一个密钥的加解密方法。
  非对称加密(又称公钥加密)指的是需要一个私有密钥一个公开密钥,两个不同的密钥的加解密体系。尽管不同,这个密钥对的这两个部分在算法上是有关联的。一个密钥将纯文本加密,另一个将密文解密。没有一个密钥能够把加密和加密的功能全部自己完成。公钥,或者用于加密数据的密钥,可以被自由分发。
  RSA 是基于大整数分解的公钥加密的算法之一。RSA 代表了 Ron Rivest、Adi Shamir 和 Leonard Adleman 三人,RSA 就是他们一起提出的。
  以下示例就展示了如何在 Java 中使用 RSA 算法对信息进行加解密。
  java.security.KeyPairGenerator 类的实例用于产生一个 RSA 算法的公钥和私钥对,之后将其保存到文件。
  javax.crypto.Cipher 类的实例用于使用上面产生的密钥对对信息进行加解密。
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.Cipher;
/**
* @author JavaDigest
*
*/
public class EncryptionUtil {
/**
* String to hold name of the encryption algorithm.
*/
public static final String ALGORITHM = "RSA";
/**
* String to hold the name of the private key file.
*/
public static final String PRIVATE_KEY_FILE = "C:/keys/private.key";
/**
* String to hold name of the public key file.
*/
public static final String PUBLIC_KEY_FILE = "C:/keys/public.key";
/**
* Generate key which contains a pair of private and public key using 1024
* bytes. Store the set of keys in Prvate.key and Public.key files.
*
* @throws NoSuchAlgorithmException
* @throws IOException
* @throws FileNotFoundException
*/
public static void generateKey() {
try {
final KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
keyGen.initialize(1024);
final KeyPair key = keyGen.generateKeyPair();
File privateKeyFile = new File(PRIVATE_KEY_FILE);
File publicKeyFile = new File(PUBLIC_KEY_FILE);
// Create files to store public and private key
if (privateKeyFile.getParentFile() != null) {
privateKeyFile.getParentFile().mkdirs();
}
privateKeyFile.createNewFile();
if (publicKeyFile.getParentFile() != null) {
publicKeyFile.getParentFile().mkdirs();
}
publicKeyFile.createNewFile();
// Saving the Public key in a file
ObjectOutputStream publicKeyOS = new ObjectOutputStream(
new FileOutputStream(publicKeyFile));
publicKeyOS.writeObject(key.getPublic());
publicKeyOS.close();
// Saving the Private key in a file
ObjectOutputStream privateKeyOS = new ObjectOutputStream(
new FileOutputStream(privateKeyFile));
privateKeyOS.writeObject(key.getPrivate());
privateKeyOS.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* The method checks if the pair of public and private key has been generated.
*
* @return flag indicating if the pair of keys were generated.
*/
public static boolean areKeysPresent() {
File privateKey = new File(PRIVATE_KEY_FILE);
File publicKey = new File(PUBLIC_KEY_FILE);
if (privateKey.exists() && publicKey.exists()) {
return true;
}
return false;
}
/**
* Encrypt the plain text using public key.
*
* @param text
*          : original plain text
* @param key
*          :The public key
* @return Encrypted text
* @throws java.lang.Exception
*/
public static byte[] encrypt(String text, PublicKey key) {
byte[] cipherText = null;
try {
// get an RSA cipher object and print the provider
final Cipher cipher = Cipher.getInstance(ALGORITHM);
// encrypt the plain text using the public key
cipher.init(Cipher.ENCRYPT_MODE, key);
cipherText = cipher.doFinal(text.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
return cipherText;
}
/**
* Decrypt text using private key.
*
* @param text
*          :encrypted text
* @param key
*          :The private key
* @return plain text
* @throws java.lang.Exception
*/
public static String decrypt(byte[] text, PrivateKey key) {
byte[] dectyptedText = null;
try {
// get an RSA cipher object and print the provider
final Cipher cipher = Cipher.getInstance(ALGORITHM);
// decrypt the text using the private key
cipher.init(Cipher.DECRYPT_MODE, key);
dectyptedText = cipher.doFinal(text);
} catch (Exception ex) {
ex.printStackTrace();
}
return new String(dectyptedText);
}
/**
* Test the EncryptionUtil
*/
public static void main(String[] args) {
try {
// Check if the pair of keys are present else generate those.
if (!areKeysPresent()) {
// Method generates a pair of keys using the RSA algorithm and stores it
// in their respective files
generateKey();
}
final String originalText = "Text to be encrypted ";
ObjectInputStream inputStream = null;
// Encrypt the string using the public key
inputStream = new ObjectInputStream(new FileInputStream(PUBLIC_KEY_FILE));
final PublicKey publicKey = (PublicKey) inputStream.readObject();
final byte[] cipherText = encrypt(originalText, publicKey);
// Decrypt the cipher text using the private key.
inputStream = new ObjectInputStream(new FileInputStream(PRIVATE_KEY_FILE));
final PrivateKey privateKey = (PrivateKey) inputStream.readObject();
final String plainText = decrypt(cipherText, privateKey);
// Printing the Original, Encrypted and Decrypted Text
System.out.println("Original: " + originalText);
System.out.println("Encrypted: " +cipherText.toString());
System.out.println("Decrypted: " + plainText);
} catch (Exception e) {
e.printStackTrace();
}
}
}
 
1
8
分享到:
评论

相关推荐

    C#与JAVA AES和RSA 加解密

    网络上很多例子看起来是对的,但实际对接中,总是对接不上,可能是两种语言差异性造成,或者是JAVA 生成密钥经过特殊处理造成,且对方又无法交流(同种语言加解密又没问题)。但C#标准方法 RSA与AES 加解密就是解不...

    RSA分段加解密java和

    rsa分段加密,附件是java和php的例子。附件中的证收是用openssl生成的测试证书。

    Android,java实现RSA加密

    RSA加密算法,是一种“由已知加密密钥推导出解密密钥在计算上是不可行的”密码体制。在公开密钥密码体制中,加密密钥(即公开密钥)PK是公开信息...本资源是通过Android、java实现的RSA加密的例子,可供大家参考学习。

    nginxRSA加密,java解密例子

    nginx里面做RSA加密需要的请求的应答,跟任何系统不相关,java解密应答

    java基于DES对称的和RSA非对称的加密解密

    工程根目录下mds5/src/com/目录下有两个例子: 其中DES.java是DES算法的对称加密解密 其中RSA.java是RSA算法的非对称加密解密 项目只给出了加密解密方法,并没有给出保存密钥的方法

    rsa_javaweb_[removed]RSA前端js加密,后端java解密 RSA 后端java加密 前端js解密

    RSA加密的内容长度有限,所以要么是只加密敏感内容,要么是结合其他对称加密例如AES使用(使用对称加密方式来加解密内容,用RSA来加解密对称加密的密钥)参考 这个已经说得挺详细了,也解决了其中遇到的一些问题,但...

    [JAVA加解密]DES,AES,PBE,DH,RSA,ElGamal等算法实现及DataServlet实例

    [JAVA加解密]DES,AES,PBE,DH,RSA,ElGamal等算法实现及DataServlet实例

    Delphi调用Java类(支持Java 6)完整源代码,可直接调试运行

    通过测试,Delphi的RSA算法无法与Java的RSA算法兼容,经过各种周折最终尝试了Delphi调用Java的类的方法进行RSA加密解密;这是非常令人振奋的解决方案,但是前期也遇到不少问题。 在网上找到...

    Java加密组件实现DES、RSA和SHA加密算法

    Java加密组件实现DES、RSA和SHA加密算法,很好的例子。

    java版web登录用RSA加密

    一个小例子,web加密登录,只有登录页面,请debug仔细看,验证时需看前台密码用md5加密后字符串跟后台解密后的字符串是否一致

    java源码包---java 源码 大量 实例

    Java图片加水印,支持旋转和透明度设置 摘要:Java源码,文件操作,图片水印  util实现Java图片水印添加功能,有添加图片水印和文字水印,可以设置水印位置,透明度、设置对线段锯齿状边缘处理、水印图片的路径,水印...

    rsa非对称加密算法例子

    RSA加密算法-Java实现,随机生产秘钥对,由公钥对内容进行加密,私钥解密。

    RSA+bcpkix-jdk15.zip

    RSA前端JS加密,后端JAVA解密实现 用RSA非对称加密方式实现。后台生成rsa密钥对,然后在页面设置rsa公钥,提交时用公钥加密密码,生成的密文传到后台,后台再用私钥解密,获取密码明文。 这样客户端只需要知道rsa...

    JAVA上百实例源码以及开源项目

    Java图片加水印,支持旋转和透明度设置 摘要:Java源码,文件操作,图片水印  util实现Java图片水印添加功能,有添加图片水印和文字水印,可以设置水印位置,透明度、设置对线段锯齿状边缘处理、水印图片的路径,水印...

    java源码包4

    Java图片加水印,支持旋转和透明度设置 摘要:Java源码,文件操作,图片水印  util实现Java图片水印添加功能,有添加图片水印和文字水印,可以设置水印位置,透明度、设置对线段锯齿状边缘处理、水印图片的路径,...

    java源码包3

    Java图片加水印,支持旋转和透明度设置 摘要:Java源码,文件操作,图片水印  util实现Java图片水印添加功能,有添加图片水印和文字水印,可以设置水印位置,透明度、设置对线段锯齿状边缘处理、水印图片的路径,...

    JAVA上百实例源码以及开源项目源代码

    Java图片加水印,支持旋转和透明度设置 摘要:Java源码,文件操作,图片水印  util实现Java图片水印添加功能,有添加图片水印和文字水印,可以设置水印位置,透明度、设置对线段锯齿状边缘处理、水印图片的路径,水印...

    java源码包2

    Java图片加水印,支持旋转和透明度设置 摘要:Java源码,文件操作,图片水印  util实现Java图片水印添加功能,有添加图片水印和文字水印,可以设置水印位置,透明度、设置对线段锯齿状边缘处理、水印图片的路径,...

    java licence生成例子

    java中使用公钥加密私钥解密原理. KeyGenerater类: public class KeyGenerater { private byte[] priKey; private byte[] pubKey; public void generater() { try { KeyPairGenerator keygen = KeyPairGenerator ...

Global site tag (gtag.js) - Google Analytics