博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
RSA算法实例
阅读量:6537 次
发布时间:2019-06-24

本文共 5986 字,大约阅读时间需要 19 分钟。

hot3.png

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 java.util.Date;

import javax.crypto.Cipher;

import org.apache.commons.codec.binary.Base64;

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](https://my.oschina.net/throws) NoSuchAlgorithmException    * [@throws](https://my.oschina.net/throws) IOException    * [@throws](https://my.oschina.net/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](https://my.oschina.net/u/556800) 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](https://my.oschina.net/u/2303379) 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();        }              long timestamp =new Date().getTime();             String originalText = "18036085116,123456,"+String.valueOf(timestamp);             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);              String enBytesStr =Base64.encodeBase64String(cipherText);      System.out.println(enBytesStr);        // 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);              inputStream.close();        // 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://my.oschina.net/xueptao/blog/1621309

你可能感兴趣的文章
(转)LINQ之路
查看>>
WCF 入门
查看>>
Linux Shell编程4
查看>>
Django REST框架--关系和超链接api
查看>>
双击防止网页放大缩小HTML5
查看>>
C#的一些学习方法
查看>>
iOS开发-开发总结
查看>>
c++中的 Stl 算法(很乱别看)
查看>>
Window 包管理工具: chocolatey
查看>>
前端开发入门 --摘自慕克网大漠穷秋
查看>>
U3D Invoke() IsInvoking CancelInvoke方法的调用
查看>>
Javascript 如何生成Less和Js的Source map
查看>>
中间有文字的分割线效果
查看>>
<悟道一位IT高管20年的职场心经>笔记
查看>>
volatile和synchronized的区别
查看>>
快速上手git
查看>>
10.30T2 二分+前缀和(后缀和)
查看>>
[emuch.net]MatrixComputations(7-12)
查看>>
vuex视频教程
查看>>
Java 线程 — ThreadLocal
查看>>