⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 rsakeypairgenerator.java

📁 对称和非对称加密
💻 JAVA
字号:
package com.dmgc.security.cipher.unsymmetic.rsa;

import com.dmgc.security.cipher.util.*;
import java.security.SecureRandom;
import java.io.*;

/**
 * <p>Title: DMGC SECURITY CIPHER LIB</p>
 * <p>Description: 上海信宁科技有限公司 安全密码库(JAVA version)</p>
 * <p>Copyright: Copyright (c) 2003</p>
 * <p>Company: 上海信宁科技有限公司</p>
 * <p>本类主要根据输入请求,随机生成一个指定长度的公钥e,然后生成n,d
 * <p>Step1 输入公钥e的长度
 * <p>Step2 随机生成一个指定长度的公钥e
 * <p>Step3 随机生成一个512比特的大素数p
 * <p>Step4 随机生成另外一个512比特的大素数q
 * <p>Step5 生成模n
 * <p>Step6 生成Phi(n)函数
 * <p>Step7 生成私钥d
 * <p>Step8 输出密钥n,e,d
 * @author 陆荣幸  周渊   潘勇
 * @version 1.0
 * @since 1.0
 */

public class RSAKeyPairGenerator {
  /**
   * 构造函数
   */
  public RSAKeyPairGenerator() {
  }

  /**
   * 用于测试
   * @param args
   */
  public static void main(String[] args) {
    try {
      RSAKeyPairGenerator RSAKeyPairGenerator1 = new RSAKeyPairGenerator();
      //
      long a = System.currentTimeMillis();
      System.out.println(a);
      DmgcMpInteger[] test = RSAKeyPairGenerator1.getKeyPair(3);
      long b = System.currentTimeMillis();
      System.out.println(b);
      System.out.println(b - a);
      for (int i = 0; i < 4; i++) {
        System.out.println(test[i].toString());
      }
      a = System.currentTimeMillis();
      System.out.println(a);
      RSAKeyPairGenerator1.getKeyPairFile(3, "D:\\lurongxing");
      b = System.currentTimeMillis();
      System.out.println(b);
      System.out.println(b - a);

    }
    catch (Exception ex) {
      ex.printStackTrace();
    }

  }

  /**
   * 生成一个指定长度的随机大素数,并且与E互素
   * @param E
   * @return 返回一个随机大素数
   */
  private DmgcMpInteger getRandomPrime(DmgcMpInteger E) {
    DmgcMpInteger returnvalue = null;

    SecureRandom random = null;
    try {
      random = SecureRandom.getInstance("SHA1PRNG");
    }
    catch (Exception ex) {
      ex.printStackTrace();
    }
    // 保证生成的随机素数大于512bit
    byte bytes[] = new byte[64];
    random.nextBytes(bytes);
    bytes[0] = (byte) (bytes[0] & (byte) (0x7f));

    // 如果最后一位是0则为偶数重新生成
    bytes[63] = (byte) (bytes[63] | (byte) (0x01));

    returnvalue = new DmgcMpInteger(bytes);

    if (returnvalue.isProbablePrime(200)) {
      // 说明是素数
    }
    else {
      random.nextBytes(bytes);
      while (! (returnvalue = new DmgcMpInteger(bytes)).isProbablePrime(200)) {
        random.nextBytes(bytes);
        bytes[0] = (byte) (bytes[0] & (byte) (0x7f));

        // 如果最后一位是0则为偶数重新生成
        bytes[63] = (byte) (bytes[63] | (byte) (0x01));

        returnvalue = new DmgcMpInteger(bytes);

      }
    }

//    if (returnvalue.signum() == -1) {
//      returnvalue = getRandomPrime(E);
//    }

    if (returnvalue.subtract(new DmgcMpInteger("1")).gcd(E).
        intValue() != 1) {
      returnvalue = getRandomPrime(E);
    }

    return returnvalue;

  }

  /**
   * 生成RSA密钥对
   * @param k  指定生成私钥d的字节数 k*8 为私钥的比特数
   * @return  DmgcMpInteger数组ret<p> ret[0] 1表示操作成功,0表示操作失败
   * .<p>ret[1] 存放大整数模n.<p>ret[2] 存放加密指数e.<p>ret[3] 存入解密指数d
   */
  public DmgcMpInteger[] getKeyPair(int k) {
    DmgcMpInteger[] ret = new DmgcMpInteger[4];
    ret[0] = new DmgcMpInteger("1");
    try {
      // 暂时存放
      RSAPrivateKey temp = new RSAPrivateKey();
      byte[] ek = DmgcMpInteger.getOddRandomByteArray(k);
      temp.setPublicExponent(new DmgcMpInteger(ek));
      //生成第一个大素数p
      temp.setPrimeP(getRandomPrime(temp.getPublicExponent()));
      //生成第二个大素数q
      boolean token = true;
      while (token) {
        temp.setPrimeQ(getRandomPrime(temp.getPublicExponent()));
        // 生成大整数模n
        temp.setModulus(temp.getPrimeP().multiply(temp.getPrimeQ()));
        if (temp.getModulus().signum() != -1) {
          token = false;
        }

      }

      // 生成PHI(N)
//      DmgcMpInteger phi = DmgcMpInteger.getPhi(compute,temp.getPrimeP());
      DmgcMpInteger phi = temp.getPrimeP().subtract(new DmgcMpInteger("1")).
          multiply(temp.getPrimeQ().subtract(new DmgcMpInteger("1")));
      // 生成私钥d
      temp.setPrivateExponent(temp.getPublicExponent().modInverse(phi));
      //
      ret[1] = temp.getModulus();
      ret[2] = temp.getPublicExponent();
      ret[3] = temp.getPrivateExponent();
      //
      temp = null;
    }
    catch (Exception ex) {
      ret[0] = new DmgcMpInteger("0");
      ex.printStackTrace();
    }
    //

    return ret;
  }

  /**
   * 生成RSA密钥对文件
   * @param k  指定生成私钥d的字节数 k*8 为私钥的比特数
   * @param filename 密钥文件的存放
   * @return boolean 类型  true 成功  false  失败
   * <p>filename.modulus   模文件
   * <p>filename.public    公钥文件
   * <p>filename.private   私钥文件
   */
  public boolean getKeyPairFile(int k, String filename) {
    boolean ret = false;

    try {
      // 暂时存放
      RSAPrivateKey temp = new RSAPrivateKey();
      byte[] ek = DmgcMpInteger.getOddRandomByteArray(k);
      temp.setPublicExponent(new DmgcMpInteger(ek));
      //生成第一个大素数p
      temp.setPrimeP(getRandomPrime(temp.getPublicExponent()));
      //生成第二个大素数q
      boolean token = true;
      while (token) {
        temp.setPrimeQ(getRandomPrime(temp.getPublicExponent()));
        // 生成大整数模n
        temp.setModulus(temp.getPrimeP().multiply(temp.getPrimeQ()));
        if (temp.getModulus().signum() != -1) {
          token = false;
        }

      }

      // 生成PHI(N)
//      DmgcMpInteger phi = DmgcMpInteger.getPhi(compute,temp.getPrimeP());
      DmgcMpInteger phi = temp.getPrimeP().subtract(new DmgcMpInteger("1")).
          multiply(temp.getPrimeQ().subtract(new DmgcMpInteger("1")));
      // 生成私钥d
      temp.setPrivateExponent(temp.getPublicExponent().modInverse(phi));
      //
      byte[] modulus = temp.getModulus().toByteArray();
      byte[] publicExponent = temp.getPublicExponent().toByteArray();
      byte[] privateExponent = temp.getPrivateExponent().toByteArray();
      //
      temp = null;
      //
      try {
        FileOutputStream modulusFileOut = new FileOutputStream(filename +
            ".modulus");
        FileOutputStream publicFileOut = new FileOutputStream(filename +
            ".public");
        FileOutputStream privateFileOut = new FileOutputStream(filename +
            ".private");

        modulusFileOut.write(modulus);
        modulusFileOut.close();
        publicFileOut.write(publicExponent);
        publicFileOut.close();
        privateFileOut.write(privateExponent);
        privateFileOut.close();
        ret = true;
      }
      catch (IOException ex) {
        ret = false;
        ex.printStackTrace();
        try {
          File test = new File(filename + ".modulus");
          test.delete();
          test = new File(filename + ".public");
          test.delete();
          test = new File(filename + ".private");
          test.delete();
        }
        catch (Exception ex1) {
          ex1.printStackTrace();
        }
      }
    }
    catch (Exception ex2) {
      ret = false;
      ex2.printStackTrace();
    }

    return ret;
  }

  /**
   * 生成RSA密钥对文件
   * @param k  指定生成私钥d的字节数 k*8 为私钥的比特数
   * @param filename 密钥文件的存放
   * @return boolean 类型  true 成功  false  失败
   * <p>filename.public    n连接e
   * <p>filename.private   n连接d
   */

  public boolean getKeyNewPairFile(int k, String filename) {
    boolean ret = false;

    try {
      // 暂时存放
      RSAPrivateKey temp = new RSAPrivateKey();
      byte[] ek = DmgcMpInteger.getOddRandomByteArray(k);
      temp.setPublicExponent(new DmgcMpInteger(ek));

//      temp.setPublicExponent(new DmgcMpInteger("259"));
      //生成第一个大素数p
      temp.setPrimeP(getRandomPrime(temp.getPublicExponent()));
      //生成第二个大素数q
      boolean token = true;
      while (token) {
        temp.setPrimeQ(getRandomPrime(temp.getPublicExponent()));
        // 生成大整数模n
        temp.setModulus(temp.getPrimeP().multiply(temp.getPrimeQ()));
        if (temp.getModulus().signum() != -1) {
          token = false;
        }

      }

      // 生成PHI(N)
//      DmgcMpInteger phi = DmgcMpInteger.getPhi(compute,temp.getPrimeP());
      DmgcMpInteger phi = temp.getPrimeP().subtract(new DmgcMpInteger("1")).
          multiply(temp.getPrimeQ().subtract(new DmgcMpInteger("1")));
      // 生成私钥d
      temp.setPrivateExponent(temp.getPublicExponent().modInverse(phi));
      //
      byte[] modulus = temp.getModulus().toByteArray();
      byte[] publicExponent = temp.getPublicExponent().toByteArray();
      byte[] privateExponent = temp.getPrivateExponent().toByteArray();
      //
      temp = null;
      //
      try {

        FileOutputStream publicFileOut = new FileOutputStream(filename +
            ".public");
        FileOutputStream privateFileOut = new FileOutputStream(filename +
            ".private");

        publicFileOut.write(modulus);
        publicFileOut.write(publicExponent);
        publicFileOut.close();

        privateFileOut.write(modulus);
        privateFileOut.write(privateExponent);
        privateFileOut.close();
        ret = true;
      }
      catch (IOException ex) {
        ret = false;
        ex.printStackTrace();
        try {
          File test =null;
          test = new File(filename + ".public");
          test.delete();
          test = new File(filename + ".private");
          test.delete();
        }
        catch (Exception ex1) {
          ex1.printStackTrace();
        }
      }
    }
    catch (Exception ex2) {
      ret = false;
      ex2.printStackTrace();
    }

    return ret;
  }

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -