Java 进行 RSA 加解密的例子

加密是保证数据安全的手段之一。加密是将纯文本数据转换为难以理解的密文;解密是将密文转换回纯文本。
数据的加解密属于密码学的范畴。通常,加密和解密都需要使用一些秘密信息,这些秘密信息叫做密钥,将纯文本转为密文或者转回的时候都要用到这些密钥。
对称加密指的是发送者和接收者共用同一个密钥的加解密方法。
非对称加密(又称公钥加密)指的是需要一个私有密钥一个公开密钥,两个不同的密钥的加解密体系。尽管不同,这个密钥对的这两个部分在算法上是有关联的。一个密钥将纯文本加密,另一个将密文解密。没有一个密钥能够把加密和加密的功能全部自己完成。公钥,或者用于加密数据的密钥,可以被自由分发。
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();
    }
  }
}

原文链接:https://javadigest.wordpress.com/2012/08/26/rsa-encryption-example/

时间: 2024-08-07 09:28:56

Java 进行 RSA 加解密的例子的相关文章

【转】 Java 进行 RSA 加解密时不得不考虑到的那些事儿

[转] Java 进行 RSA 加解密时不得不考虑到的那些事儿 1. 加密的系统不要具备解密的功能,否则 RSA 可能不太合适 公钥加密,私钥解密.加密的系统和解密的系统分开部署,加密的系统不应该同时具备解密的功能,这样即使黑客攻破了加密系统,他拿到的也只是一堆无法破解的密文数据.否则的话,你就要考虑你的场景是否有必要用 RSA 了. 2. 可以通过修改生成密钥的长度来调整密文长度 生成密文的长度等于密钥长度.密钥长度越大,生成密文的长度也就越大,加密的速度也就越慢,而密文也就越难被破解掉.著名

Java 进行 RSA 加解密时不得不考虑到的那些事儿

1. 加密的系统不要具备解密的功能,否则 RSA 可能不太合适 公钥加密,私钥解密.加密的系统和解密的系统分开部署,加密的系统不应该同时具备解密的功能,这样即使黑客攻破了加密系统,他拿到的也只是一堆无法破解的密文数据.否则的话,你就要考虑你的场景是否有必要用 RSA 了. 2. 可以通过修改生成密钥的长度来调整密文长度 生成密文的长度等于密钥长度.密钥长度越大,生成密文的长度也就越大,加密的速度也就越慢,而密文也就越难被破解掉.著名的"安全和效率总是一把双刃剑"定律,在这里展现的淋漓尽

java中RSA加解密的实现

今天在做RSA加密的时候遇到了一个这样的错误:ArrayIndexOutOfBoundsException: too much data for RSA block 查询相关资料后得知该错误是加密数据过长导致的. 加密数据长度 <= 模长-11 解决办法:将要加密的数据截取后分段加密 1.密钥长度rsa算法初始化的时候一般要填入密钥长度,在96-1024bits间(1)为啥下限是96bits(12bytes)?因为加密1byte的明文,需要至少1+11=12bytes的密钥(不懂?看下面的明文长

用Java实现RSA加解密及签名和验签(1)——.pem文件格式秘钥

一.***.pem文件格式的秘钥(获取秘钥:可通过文件读取内容或者直接打开文件复制内容),我这里是打开文件复制秘钥直接使用 1.准备秘钥对,通过openssl生成秘钥对,生成秘钥可参考:https://www.cnblogs.com/ouyanxia/p/12427955.html A_RSA_PRIVATE_KEY=-----BEGIN PRIVATE KEY-----MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDnPzYKf20JIza

用Java实现RSA加解密及签名和验签(2)——.pfx文件格式秘钥

注:.pfx 主要用于windows平台,浏览器可以使用,也是包含证书和私钥,获取私钥需要密码才可以 .pfx文件生成的方式可参考:https://www.cnblogs.com/ouyanxia/p/12427955.html 1.准备好pfx秘钥文件(alias默认是1) path=/RSA/other/openssl.pfx pwd=秘钥的秘钥(生成秘钥时记得存好) alias=1 cerPath=/RSA/other/openssl.cer 2.编写RSAUtil import java

java rsa加解密算法的实现

RSAUtils:RSA加解密的实现 package com.rsa.test; import java.io.ByteArrayOutputStream; import java.nio.charset.Charset; import java.security.Key; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import jav

java RSA加解密以及用途

在公司当前版本的中间件通信框架中,为了防止非授权第三方和到期客户端的连接,我们通过AES和RSA两种方式的加解密策略进行认证.对于非对称RSA加解密,因为其性能耗费较大,一般仅用于认证连接,不会用于每次报文本身的加解密(这一般使用AES/DES加密),对于较为安全的支付通道,则一般是约定定期交换加解密密钥,交换过程本身的报文则是通过RSA进行加解密的.这样就在单纯的对称加密的基础上提供了更好的保障,只要签名复杂,定期的更新足以使得破坏的成本高昂到超过破解的成本. 一般来说,公钥会发布给客户端,客

java 使用pem密钥进行RSA加解密

1.使用openssl生成私钥和公钥 openssl下载地址:http://www.openssl.org/source openssl生成私钥命令:  genrsa -out rsa_private_key.pem 1024 openssl生成公钥命令:  rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem 2.此时在openssl安装目录下的bin文件夹可以看到 rsa_private_key.pem 和 rsa_publi

Java和C# RSA加解密相互通信和使用公钥加密传输

关于JAVA和C#加解密通讯的话,可以用这个BouncyCastle插件,会帮助你解决很多问题 http://www.bouncycastle.org/ //c#使用java给的公钥进行rsa加密 public static byte[] RSAEncrypt(string publickey, string content) { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); byte[] publicKeyByte