美文网首页
JAVA生成X509证书

JAVA生成X509证书

作者: wlyhl | 来源:发表于2018-09-06 18:54 被阅读0次

    Java生成RSA密钥对的两种方法:

    1、RSAPublicKeySpec和RSAPrivateCrtKeySpec

    这两个API是JAVA安全模块自带的API,可以查看API的相关说明:

    public RSAPublicKeySpec(BigInteger modulus,BigInteger

    publicExponent)

    创建一个新的RSAPublicKeySpec。

    参数

    modulus - 模数

    publicExponent - 公钥指数

    publicRSAPrivateCrtKeySpec(BigInteger modulus,

                                BigIntegerpublicExponent,

                                BigInteger privateExponent,

                                BigInteger primeP,

                                BigInteger primeQ,

                                BigIntegerprimeExponentP,

                                BigIntegerprimeExponentQ,

                                BigInteger crtCoefficient)

    创建一个新的RSAPrivateCrtKeySpec给定在PKCS#1中定义的模数,publicExponent,privateExponent,primeP,primeQ,primeExponentP,primeExponentQ和crtCoefficient。

    参数

    modulus - 模数n

    publicExponent - 公钥指数e

    privateExponent -私钥指数d

    primeP - n的素因子p

    primeQ - n的素因子q

    primeExponentP - 这是d mod(p-1)

    primeExponentQ - 这是d mod(q-1)

    crtCoefficient - 剩余定理系数q-1 mod p

    示例代码如下:

    // 创建指定公钥的对象

    RSAPublicKeySpec localRSAPublicKeySpec1 =

    new RSAPublicKeySpec(new

    BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7",

    16), new BigInteger("11", 16));

    // 创建指定私钥的对象

    RSAPrivateCrtKeySpec

    localRSAPrivateCrtKeySpec1 = new RSAPrivateCrtKeySpec(new

    BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7",

    16), new BigInteger("11", 16), new

    BigInteger("9f66f6b05410cd503b2709e88115d55daced94d1a34d4e32bf824d0dde6028ae79c5f07b580f5dce240d7111f7ddb130a7945cd7d957d1920994da389f490c89",

    16), new

    BigInteger("c0a0758cdf14256f78d4708c86becdead1b50ad4ad6c5c703e2168fbf37884cb",

    16), new BigInteger("f01734d7960ea60070f1b06f2bb81bfac48ff192ae18451d5e56c734a5aab8a5",

    16), new

    BigInteger("b54bb9edff22051d9ee60f9351a48591b6500a319429c069a3e335a1d6171391",

    16), new BigInteger("d3d83daf2a0cecd3367ae6f8ae1aeb82e9ac2f816c6fc483533d8297dd7884cd",

    16), new BigInteger("b8f52fc6f38593dabb661d3f50f8897f8106eee68b1bce78a95b132b4e5b5d19",

    16));

    // 创建指定RSA算法的密钥工厂,指定工厂为BC

    KeyFactory localKeyFactory =

    KeyFactory.getInstance("RSA", "BC");

    // 生成私钥

    PrivateKey localPrivateKey1 =

    localKeyFactory.generatePrivate(localRSAPrivateCrtKeySpec1);

    // 生成公钥

    PublicKey localPublicKey1 =

    localKeyFactory.generatePublic(localRSAPublicKeySpec1);

    2、KeyPair 和KeyPairGenerator

    KeyPairGenerator类用于生成公钥和私钥对。 密钥对生成器使用getInstance工厂方法(返回给定类的实例的静态方法)构造。

    用于特定算法的密钥对生成器创建可以与该算法一起使用的公钥/私钥对。 它还将算法特定的参数与生成的每个密钥相关联。

    生成密钥对的方法有两种:以算法无关的方式,并以算法特定的方式。

    publicKeyPair(PublicKey publicKey, PrivateKey privateKey)

    从给定的公钥和私钥构造一个密钥对。

    请注意,此构造函数仅存储对生成的密钥对中的公钥和私钥组件的引用。 这是安全的,因为Key对象是不可变的。

    参数

    publicKey - 公钥。

    privateKey - 私钥。

    示例代码如下:

    // 生成RSA公私钥对

    KeyPairGenerator kpg = null;

    // 采用 RSA 非对称算法加密

    kpg =KeyPairGenerator.getInstance("RSA");

    // 初始化为2048 位

    kpg.initialize(2048);

    KeyPair keyPair = kpg.generateKeyPair();

    // 公钥

    PublicKey pubKey =localKeyFactory.generatePublic(localRSAPublicKeySpec1);

    // 私钥

    PrivateKey priKey = keyPair.getPrivate();

    3、完整的示例代码

    packagecom.test;

    importjava.io.File;

    importjava.io.FileOutputStream;

    importjava.io.IOException;

    importjava.math.BigInteger;

    importjava.security.KeyPair;

    importjava.security.KeyPairGenerator;

    importjava.security.PrivateKey;

    importjava.security.PublicKey;

    importjava.security.Security;

    importjava.security.cert.CertificateEncodingException;

    import java.security.cert.X509Certificate;

    importjava.util.Calendar;

    importjava.util.Date;

    importjava.util.Hashtable;

    importjava.util.Vector;

    importorg.bouncycastle.asn1.x509.KeyUsage;

    importorg.bouncycastle.asn1.x509.X509Extension;

    importorg.bouncycastle.jce.X509Principal;

    importorg.bouncycastle.jce.provider.BouncyCastleProvider;

    importorg.bouncycastle.x509.X509V3CertificateGenerator;

    @SuppressWarnings("deprecation")

    public class GenCrt {

      /**

        *BouncyCastleProvider

        */

       static {

          Security.addProvider(new BouncyCastleProvider());

       }

     /**

        *生成 X509 证书

        *@param user

        *@return

        */

       @SuppressWarnings({ "deprecation", "unchecked" })

       public static byte[] generateCert() {

          X509Certificatecert = null;

          X509V3CertificateGeneratorcertGen=new X509V3CertificateGenerator();

          try {

             // 生成RSA公私钥对

             KeyPairGeneratorkpg = null;

             // 采用 RSA 非对称算法加密

             kpg= KeyPairGenerator.getInstance("RSA");

             // 初始化为2048 位

             kpg.initialize(2048);

             KeyPairkeyPair = kpg.generateKeyPair();

             // 公钥

             PublicKeypubKey = keyPair.getPublic();

             // 私钥

             PrivateKeypriKey = keyPair.getPrivate();

             // 公钥

             certGen.setPublicKey(pubKey);

             // 设置序列号

             certGen.setSerialNumber(new BigInteger("12345678"));

             // 设置颁发者信息

             @SuppressWarnings("rawtypes")

             HashtablekwMapIssuer = new Hashtable();

              @SuppressWarnings("rawtypes")

             VectorlocalVector = new Vector();

             kwMapIssuer.put(X509Principal.C,"CN");

             localVector.addElement(X509Principal.C);

             kwMapIssuer.put(X509Principal.CN,"wuwu");

             localVector.addElement(X509Principal.CN);

             kwMapIssuer.put(X509Principal.E, "111@qq.com");

             localVector.addElement(X509Principal.E);

             certGen.setIssuerDN(new X509Principal(localVector, kwMapIssuer));

             //  设置申请者信息

             @SuppressWarnings("rawtypes")

             HashtablekwMapApplicant = new Hashtable();

              @SuppressWarnings("rawtypes")

             VectorlocalVectorApplicant = new Vector();

             kwMapApplicant.put(X509Principal.C,"CN");

             localVectorApplicant.addElement(X509Principal.C);

             kwMapApplicant.put(X509Principal.CN,"wlhl");

             localVectorApplicant.addElement(X509Principal.CN);

             kwMapApplicant.put(X509Principal.E, "123@qq.com");

             localVectorApplicant.addElement(X509Principal.E);

             certGen.setSubjectDN(new X509Principal(localVectorApplicant, kwMapApplicant));

             // 设置有效期

             Calendarc= Calendar.getInstance();

             c.set(Calendar.DAY_OF_YEAR, c.get(Calendar.DAY_OF_YEAR) + 7000);

             certGen.setNotBefore(new Date());

             certGen.setNotAfter(c.getTime());

             // 设置扩展域,密钥用途

             certGen.addExtension(X509Extension.keyUsage, false, new KeyUsage(KeyUsage.digitalSignature));

                // 签名算法

             certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

             cert = certGen.generateX509Certificate(priKey, "BC");

          }catch (Exception e) {

             System.out.println(e.getClass() + e.getMessage());

          }

          try {

             return cert.getEncoded();

          }catch (CertificateEncodingException e) {

             // TODO Auto-generated catch block

             e.printStackTrace();

             return null;

          }

       }

       /**

        *写文件

        *@param name

        *@param data

        */

       static public void writeFile(String name, byte[] data) {

          if(data == null)

          {

             return;

          }

          FileOutputStreamfop = null;

          try {

             fop = new FileOutputStream(new File(name));

             fop.write(data);

             fop.close();

          }catch (IOException e) {

             // TODO Auto-generated catch block

             e.printStackTrace();

          }

       }

       public static void main(String[] args) {

          // TODOAuto-generated method stub

          byte[] crtBuf=generateCert();

          if(crtBuf != null) {

             writeFile("./TestCrt.crt", crtBuf);

          }

       }

    }

    生成后的效果:

    相关文章

      网友评论

          本文标题:JAVA生成X509证书

          本文链接:https://www.haomeiwen.com/subject/suffgftx.html