`

RSA算法

 
阅读更多
package qeeka.test.qeeka.test;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
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.Signature;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
  
/* 
* To change this license header, choose License Headers in Project Properties. 
* To change this template file, choose Tools | Templates 
* and open the template in the editor. 
*/  
/** 

* @author Neil 

* To provide a wrapper class for RSA operations,including key 
* generation,encryption,decryption,signing and signature verification. RSA can 
* be used in the several ways: Encrypt the content using . 
*/  
public class RSAHelper {  
  
    /** 
     * Key algorithm to be used in this class. 
     */  
    public static final String KEY_ALGORITHM = "RSA";  
  
    /** 
     * Default key length. The value shall be in the range of 512-65536. 
     */  
    private static final int KEY_LENGTH = 1024;  
  
    /** 
     * Identifier of pubic key in the Map. 
     */  
    public static final String PUBLIC_KEY = "PublicKey";  
  
    /** 
     * Identifier of private key in the Map. 
     */  
    public static final String PRIVATE_KEY = "PrivateKey";  
  
    /** 
     * Algorithm to be used for signature and verification. 
     */  
    private static final String SIGNATURE_ALGORITHM = "MD5withRSA";  
  
    /** 
     * Generate a RSA key pair with public key and private key. 
     * 
     * @param keyMap to save the key pair, the public key is indicated by 
     * "PublicKey" and private key is indicated by "PrivateKey". 
     * @return 
     */  
    public static Result generateKeyPair(Map<String, Object> keyMap) {  
        Result result = new Result();  
        //Get one instance of KeyPairGenerator with RSA.  
        KeyPairGenerator keyPairGenerator = null;  
        try {  
            keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);  
        } catch (NoSuchAlgorithmException ex) {  
            Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null, ex);  
            result.setFailure();  
        }  
  
        if (result.isSuccess()) {  
            //Get a random seed.  
            SecureRandom secureRandom = new SecureRandom();  
  
            //Use current datetime as random seed.  
            String currentDateTime = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());  
            secureRandom.setSeed(currentDateTime.getBytes());  
  
            //Initialze the key generator with the random number provider. We need to call initialze everytime to get a NEW key pair.  
            keyPairGenerator.initialize(KEY_LENGTH, secureRandom);  
  
            //Ready to generate a key pair.  
            KeyPair keyPair = keyPairGenerator.genKeyPair();  
  
            //Get public and private key.  
            PublicKey publicKey = keyPair.getPublic();  
            PrivateKey privateKey = keyPair.getPrivate();  
  
            keyMap.put(PUBLIC_KEY, publicKey.getEncoded());  
            keyMap.put(PRIVATE_KEY, privateKey.getEncoded());  
        }  
  
        return result;  
    }  
  
    /** 
     * Save the keys into the key file. 
     * 
     * @param keyPair key pair to be saved into the file. 
     * @param publicKeyFileName file to save public key. 
     * @param privateKeyFileName file to save private key. 
     */  
    public static void saveKeyPair(Map<String, Object> keyPair, String publicKeyFileName, String privateKeyFileName) {  
        //Write public key into the key file.  
        try {  
            FileOutputStream fileOutputStream = new FileOutputStream(publicKeyFileName);  
            byte[] publicKey = (byte[]) keyPair.get(PUBLIC_KEY);  
            fileOutputStream.write(publicKey);  
            fileOutputStream.close();  
        } catch (FileNotFoundException ex) {  
            Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null, ex);  
        } catch (IOException ex) {  
            Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null, ex);  
        }  
  
        //Write private key into the key file.  
        try {  
            FileOutputStream fileOutputStream = new FileOutputStream(privateKeyFileName);  
            byte[] privateKey = (byte[]) keyPair.get(PRIVATE_KEY);  
            fileOutputStream.write(privateKey);  
            fileOutputStream.close();  
        } catch (FileNotFoundException ex) {  
            Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null, ex);  
        } catch (IOException ex) {  
            Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null, ex);  
        }  
    }  
  
    /** 
     * Get the key from local file. 
     * 
     * @param keyFileName file containing the key. 
     * 
     * @return byte array containing the key. 
     */  
    public static byte[] getKey(String keyFileName) {  
        byte[] keyBytes = null;  
        //Get key from file.  
        try {  
            File file = new File(keyFileName);  
            FileInputStream fileInputStream = new FileInputStream(file);  
            DataInputStream dataInputStream = new DataInputStream(fileInputStream);  
  
            //Allocate the buffer.  
            keyBytes = new byte[(int) file.length()];  
  
            //Read them all.  
            dataInputStream.readFully(keyBytes);  
  
            dataInputStream.close();  
            fileInputStream.close();  
        } catch (FileNotFoundException ex) {  
            Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null, ex);  
        } catch (IOException ex) {  
            Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null, ex);  
        }  
  
        return keyBytes;  
    }  
  
    /** 
     * Encrypt the data with the public key. 
     * 
     * @param data data to be encrypted. 
     * @param offset offset of data to be encrypted. 
     * @param length length of data to be encrypted. 
     * @param publicKeyBytes public key in binary format. 
     * @return encrypted data. 
     */  
    public static byte[] encryptWithPublicKey(byte[] data, int offset, int length, byte[] publicKeyBytes) {  
  
        byte[] encryptedData = null;  
  
        try {  
            //Create a new X509EncodedKeySpec with the given encoded key.  
            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKeyBytes);  
  
            //RSA key factory.  
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);  
  
            //Get the public key from the provided key specification.  
            PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);  
  
            //Init the ciper.  
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());  
  
            //Encrypt mode!  
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);  
  
            //Do the encryption now !!!!  
            encryptedData = cipher.doFinal(data, offset, length);  
  
        } catch (NoSuchAlgorithmException ex) {  
            Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null, ex);  
        } catch (InvalidKeySpecException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          } catch (NoSuchPaddingException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          } catch (IllegalBlockSizeException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          } catch (BadPaddingException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          } catch (InvalidKeyException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          }  
  
        return encryptedData;  
    }  
  
    /** 
     * Encrypt the data with private key. 
     * 
     * @param data data to be encrypted. 
     * @param offset offset of data to be encrypted. 
     * @param length length of data to be encrypted. 
     * @param privateKeyBytes private key in binary format. 
     * @return encrypted data. 
     */  
    public static byte[] encryptWithPrivateKey(byte[] data, int offset, int length, byte[] privateKeyBytes) {  
        byte[] encryptedData = null;  
  
        try {  
            // Create a new PKCS8EncodedKeySpec with the given encoded key.  
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);  
  
            //RSA key factory.  
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);  
  
            //Get the private key from the provided key specification.  
            PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);  
  
            //Init the ciper.  
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());  
  
            //Encrypt mode!  
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);  
  
            //Do the encryption now !!!!  
            encryptedData = cipher.doFinal(data, offset, length);  
  
        } catch (NoSuchAlgorithmException ex) {  
            Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null, ex);  
        } catch (InvalidKeySpecException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          } catch (NoSuchPaddingException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          } catch (IllegalBlockSizeException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          } catch (BadPaddingException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          } catch (InvalidKeyException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          }  
        return encryptedData;  
    }  
  
    /** 
     * Decrypt data with public key. 
     * 
     * @param data data to be decrypted. 
     * @param offset offset of data to be decrypted. 
     * @param length length of data to be decrypted. 
     * @param publicKeyBytes public key in binary format. 
     * @return decrypted data. 
     */  
    public static byte[] decryptWithPublicKey(byte[] data, int offset, int length, byte[] publicKeyBytes) {  
  
        byte[] encryptedData = null;  
  
        try {  
            //Create a new X509EncodedKeySpec with the given encoded key.  
            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKeyBytes);  
  
            //RSA key factory.  
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);  
  
            //Get the public key from the provided key specification.  
            PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);  
  
            //Init the ciper.  
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());  
  
            //Decrypt mode!  
            cipher.init(Cipher.DECRYPT_MODE, publicKey);  
  
            //Do the decryption now !!!!  
            encryptedData = cipher.doFinal(data, offset, length);  
  
        } catch (NoSuchAlgorithmException ex) {  
            Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null, ex);  
        } catch (InvalidKeySpecException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          } catch (NoSuchPaddingException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          } catch (IllegalBlockSizeException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          } catch (BadPaddingException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          } catch (InvalidKeyException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          }  
  
        return encryptedData;  
    }  
  
    /** 
     * Decrypt the data with private key bytes. 
     * 
     * @param data data to be decrypted. 
     * @param offset offset of data to be decrypted. 
     * @param length length of data to be decrypted. 
     * @param privateKeyBytes private key in binary format. 
     * @return decrypted data. 
     */  
    public static byte[] decryptWithPrivateKey(byte[] data, int offset, int length, byte[] privateKeyBytes) {  
        byte[] encryptedData = null;  
  
        try {  
            // Create a new PKCS8EncodedKeySpec with the given encoded key.  
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);  
  
            //RSA key factory.  
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);  
  
            //Get the private key from the provided key specification.  
            PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);  
  
            //Init the ciper.  
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());  
  
            //Decrypt mode!  
            cipher.init(Cipher.DECRYPT_MODE, privateKey);  
  
            //Do the decryption now !!!!  
            encryptedData = cipher.doFinal(data, offset, length);  
  
        } catch (NoSuchAlgorithmException ex) {  
            Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null, ex);  
        } catch (InvalidKeySpecException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          } catch (NoSuchPaddingException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          } catch (IllegalBlockSizeException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          } catch (BadPaddingException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          } catch (InvalidKeyException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          }   
  
        return encryptedData;  
    }  
  
    /** 
     * Decrypt the data with private key. 
     * 
     * @param data data to be decrypted. 
     * @param offset offset of data to be decrypted. 
     * @param length length of data to be decrypted. 
     * @param privateKey private key. 
     * @return decrypted data. 
     */  
    public static byte[] decryptWithPrivateKey(byte[] data, int offset, int length, PrivateKey privateKey) {  
        byte[] encryptedData = null;  
  
        try {  
            //RSA key factory.  
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);  
  
  
            //Init the ciper.  
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());  
  
            //Decrypt mode!  
            cipher.init(Cipher.DECRYPT_MODE, privateKey);  
  
            //Do the decryption now !!!!  
            encryptedData = cipher.doFinal(data, offset, length);  
  
        } catch (NoSuchAlgorithmException ex) {  
            Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null, ex);  
        } catch (NoSuchPaddingException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          } catch (IllegalBlockSizeException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          } catch (BadPaddingException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          } catch (InvalidKeyException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          }  
  
        return encryptedData;  
    }  
      
    /** 
     * Sign the data with the private key. 
     * 
     * @param data data to be signed. 
     * @param offset offset of data to be signed. 
     * @param length length of data to be signed. 
     * @param privateKeyBytes private key in binary format. 
     * @return signed data. 
     */  
    public static byte[] sign(byte[] data, int offset, int length, byte[] privateKeyBytes) {  
        byte[] signedData = null;  
        try {  
            // Create a new PKCS8EncodedKeySpec with the given encoded key.  
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);  
  
            //RSA key factory.  
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);  
  
            //Get the private key from the provided key specification.  
            PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);  
  
            //Create the Signature instance with RSA MD5.  
            Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);  
  
            //Use private key to do the signature.  
            signature.initSign(privateKey);  
  
            //Updates the data to be signed or verified, using the specified array of bytes.  
            signature.update(data, offset, length);  
  
            //Sign it now.  
            signedData = signature.sign();  
        } catch (NoSuchAlgorithmException ex) {  
            Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null, ex);  
        } catch (InvalidKeySpecException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
        }catch (InvalidKeyException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          } catch (SignatureException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          } 
  
        return signedData;  
    }  
  
    /** 
     * Verify the signature. 
     * 
     * @param data data signed. 
     * @param offset offset of data to be verified. 
     * @param length length of data to be verified. 
     * @param publicKeyBytes public key in binary format. 
     * @param dataSignature signature for the data. 
     * @return Whether the signature is fine. 
     */  
    public static boolean verify(byte[] data, int offset, int length, byte[] publicKeyBytes, byte[] dataSignature) {  
        boolean result = false;  
        try {  
            //Create a new X509EncodedKeySpec with the given encoded key.  
            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKeyBytes);  
  
            //RSA key factory.  
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);  
  
            //Get the public key from the provided key specification.  
            PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);  
  
            //Create the Signature instance with RSA MD5.  
            Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);  
  
            //Use pubic key to verify the signature.  
            signature.initVerify(publicKey);  
  
            //Updates the data to be signed or verified, using the specified array of bytes.  
            signature.update(data, offset, length);  
  
            //Verifies the passed-in signature.  
            result = signature.verify(dataSignature);  
  
        } catch (NoSuchAlgorithmException ex) {  
            Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null, ex);  
        } catch (InvalidKeySpecException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          } catch (InvalidKeyException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          } catch (SignatureException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          } 
  
        return result;  
    }  
    
    public static void main(String args[]) throws UnsupportedEncodingException{
         Map<String, Object> putKey = new HashMap<String, Object>();
         generateKeyPair(putKey);
         System.out.println(putKey.get(PUBLIC_KEY));
         System.out.println(putKey.get(PRIVATE_KEY));
         byte[] encryByte = encryptWithPublicKey("念数成金".getBytes("UTF-8"), 0, "念数成金".getBytes("UTF-8").length, (byte[])putKey.get(PUBLIC_KEY));
         
         System.out.println(new String(decryptWithPrivateKey(encryByte, 0,
                    encryByte.length, (byte[]) putKey.get(PRIVATE_KEY)),"UTF-8"));
         
    }
}
 
package qeeka.test.qeeka.test;
 
public class Result {
 
       private Boolean operateFlag= true;
      
       public void setFailure(){
             operateFlag = false;
      }
      
       public Boolean isSuccess(){
             return operateFlag;
      }
 
       public Boolean getOperateFlag() {
             return operateFlag;
      }
 
       public void setOperateFlag(Boolean operateFlag) {
             this. operateFlag = operateFlag;
      }
      
      
}
分享到:
评论

相关推荐

    RSA算法演示RSA算法演示

    RSA算法演示RSA算法演示RSA算法演示RSA算法演示RSA算法演示RSA算法演示RSA算法演示RSA算法演示RSA算法演示RSA算法演示RSA算法演示

    RSA.rar_RSA算法_寻找大素数 rsa_数论算法_简单数论

    RSA算法基于一个十分简单的数论事实:将两个大素数相乘十分容易,但是想要对其乘积进行因式分解却极其困难,因此可以将乘积公开作为加密密钥。RSA算法是第一个能同时用于加密和数字签名的算法,也易于理解和操作。...

    RSA实现算法报告关于RSA算法的实现代码

    RSA实现算法报告关于RSA算法的实现代码

    RSA算法工具 RSA算法

    RSA算法工具RSA算法工具RSA算法工具RSA算法工具 RSA算法工具

    VC++实现RSA算法

    VC++实现RSA算法

    RSA算法演示.rar

    RSA算法演示.rar

    RSA算法的纯Python实现(源码)

    RSA算法的纯Python实现,压缩包内共4个文件,分别是 1、大整数的运算库(当然不是算加减乘除的,这个python本身就有)。这个库是计算乘模运算,幂模运算(蒙哥马利算法),最大公约数算法及扩展最大公约数算法(扩展...

    RSA算法的C实现

    MFC界面 相当于一个用RSA算法实现的加密小软件

    读硬盘序列号和加密RSA算法.rar

    读硬盘序列号和加密RSA算法.rar 读硬盘序列号和加密RSA算法.rar

    数字签名 RSA算法 c++

    包涵三个RSA算法,c++是实现,数字签名的合集,三个独自的程序,可以独自编译运行,VC6.0下编译 包涵三个RSA算法,c++是实现,数字签名的合集,三个独自的程序,可以独自编译运行,VC6.0下编译

    RSA算法加解密

    RSA算法加解密 详细介绍RSA算法的思想 附代码 很详细 绝对非常有用!!

    RSA算法试验报告

    目前的公开密钥算法大部分基于大整数分解、有限域上的离散对数问题和椭圆曲线上的离散对数问题,这些数学难题的构建大部分都需要生成一种超大的素数,尤其在经典的 RSA算法中,生成的素数的质量对系统的安全性有很大...

    rsa算法

    rsa算法

    密码学RSA算法实现代码

    密码学中的RSA 算法的java代码实现,其中有模的重复平方计算法和中国剩余定理

    中国剩余定理在RSA算法中应用的研究详细实验

    RSA算法中模数和运算效率之间一直存在矛盾,目前一些认证机构已采用模数为 2048 bit 的 RSA 签名方法,这必然会影响签名效率。中国剩余定理对于提高RSA算法的模幂乘运算效率有显著作用,被广泛地应用在加速私钥解密...

    易语言RSA算法演示

    易语言RSA算法演示源码,RSA算法演示

    RSA算法C++实现

    RSA算法C++实现 RSA算法C++实现

    RSA算法优化及改进

    1.RSA算法的编程 2.编程改进原RSA算法,在运算速率上优化RSA算法(最好有前后两个程序速率的对比) 3.简单应用优化后的RSA算法(简单对一个文件加密)

    Delphi中的经典RSA算法源码示例

    delphi RSA算法示例以及源码,已经修改为XE系列可用代码,支持中文,可以直接拿来用,用来进行加密和解密

    RSA算法,VC 实现算法,附测试程序

    RSA算法,VC 实现算法,附测试程序 RSA算法,VC 实现算法,附测试程序 RSA算法,VC 实现算法,附测试程序

Global site tag (gtag.js) - Google Analytics