欢迎来到天天文库
浏览记录
ID:55954404
大小:16.50 KB
页数:3页
时间:2020-06-18
《pki java相关代码实现.doc》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、pkijava相关代码实现keytool-genkey-dname"CN=demo,OU=softDept,O=company,L=puddong,S=shanghai,C=cn"-alias demo-keyalgRSA-keysize1024-keystoredemoKeystore-validity3650-storepass storePwd-keypassdemoPwd生成保存公钥和私钥的密钥仓库,保存在demoKeystore文件中。这里storepass 和keypass不要有java正则表达式中的特殊字符
2、,否则程序里要转义麻烦。keytool-export-alias demo-keystoredemoKeystore-rfc-filedemo.cer//从密钥仓库中导出保存公钥的证书输入keypass即demoPwd try{ //密钥仓库 KeyStoreks=KeyStore.getInstance("JKS");//读取密钥仓库 FileInputStreamksfis=newFileInputStream("demoKeystore"); BufferedInputStreamks
3、bufin=newBufferedInputStream(ksfis); char[]storePwd="storePwd".toCharArray(); ks.load(ksbufin,storePwd); ksbufin.close(); char[]keyPwd="demoPwd".toCharArray();//从密钥仓库得到私钥 PrivateKeypriK=(PrivateKey)ks.getKey("demo",keyPwd); //生成cipher Ciphercipher=Ci
4、pher.getInstance("RSA/ECB/PKCS1Padding",neworg.bouncycastle.jce.provider.BouncyCastleProvider());//用私钥初始化cipher cipher.init(Cipher.ENCRYPT_MODE,priK); byte[]plain="Thisisplaintext".getBytes("UTF-8"); //因为用的1024位rsa算法,一次只能加密1024/8-11字节数据,分开加密 byte[]code
5、=newbyte[(((plain.length-1)/117+1))*128]; intixplain=0; intixcode=0; while((plain.length-ixplain)>117){//每117字节做一次加密 ixcode+=cipher.doFinal(plain,ixplain,117,code,ixcode); ixplain+=117; }
6、 cipher.doFinal(plain,ixplain,plain.length-ixplain,code,ixcode); //加密后的code System.out.println(Arrays.toString(code)); //通常会用base64编码 Stringbase64=encoder.encode(code); CertificateFactorycertificatefactory=Certificat
7、eFactory .getInstance("X.509"); //读取证书 FileInputStreamfin=newFileInputStream("demo.cer"); X509Certificatecertificate=(X509Certificate)certificatefactory .generateCertificate(fin); fin.close(); //得到公钥 PublicKeypubK=certificate.getPublicKey();
8、 //初始化cipher cipher.init(Cipher.DECRYPT_MODE,pubK); //base64解码 code=decoder.decodeBuffer(base64); System.out.println(A
此文档下载收益归作者所有