用Java编写一个程序,生成公钥和私钥对一java公私钥生成代码:需要包含的包
import java.security.*;
import java.io.*;
import java.util.*;
import java.security.*;
import java.security.cert.*;
import sun.security.x509.*
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
二:从文件中读取证书
用keytool将.keystore中的证书写入文件中java公私钥生成代码 , 然后从该文件中读取证书信息
CertificateFactory cf=CertificateFactory.getInstance("X.509");
FileInputStream in=new FileInputStream("out.csr");
Certificate c=cf.generateCertificate(in);
String s=c.toString();
三:从密钥库中直接读取证书
String pass="123456";
FileInputStream in=new FileInputStream(".keystore");
KeyStore ks=KeyStore.getInstance("JKS");
ks.load(in,pass.toCharArray());
java.security.cert.Certificate c=ks.getCertificate(alias);//alias为条目的别名
四:JAVA程序中显示证书指定信息
System.out.println("输出证书信息:\n" c.toString());
System.out.println("版本号:" t.getVersion());
System.out.println("序列号:" t.getSerialNumber().toString(16));
System.out.println("主体名:" t.getSubjectDN());
System.out.println("签发者:" t.getIssuerDN());
System.out.println("有效期:" t.getNotBefore());
System.out.println("签名算法:" t.getSigAlgName());
byte [] sig=t.getSignature();//签名值
PublicKey pk=t.getPublicKey();
byte [] pkenc=pk.getEncoded();
System.out.println("公钥");
for(int i=0;ipkenc.length;i)System.out.print(pkenc[i] ",");
五:JAVA程序列出密钥库所有条目
String pass="123456";
FileInputStream in=new FileInputStream(".keystore");
KeyStore ks=KeyStore.getInstance("JKS");
ks.load(in,pass.toCharArray());
Enumeration e=ks.aliases();
while(e.hasMoreElements())
java.security.cert.Certificate c=ks.getCertificate((String)e.nextElement());
六:JAVA程序修改密钥库口令
String oldpass="123456";
String newpass="654321";
FileInputStream in=new FileInputStream(".keystore");
KeyStore ks=KeyStore.getInstance("JKS");
ks.load(in,oldpass.toCharArray());
in.close();
FileOutputStream output=new FileOutputStream(".keystore");
ks.store(output,newpass.toCharArray());
output.close();
七:JAVA程序修改密钥库条目的口令及添加条目
FileInputStream in=new FileInputStream(".keystore");
KeyStore ks=KeyStore.getInstance("JKS");
ks.load(in,storepass.toCharArray());
Certificate [] cchain=ks.getCertificate(alias);获取别名对应条目的证书链
PrivateKey pk=(PrivateKey)ks.getKey(alias,oldkeypass.toCharArray());获取别名对应条目的私钥
ks.setKeyEntry(alias,pk,newkeypass.toCharArray(),cchain);向密钥库中添加条目
第一个参数指定所添加条目的别名,假如使用已存在别名将覆盖已存在条目,使用新别名将增加一个新条目,第二个参数为条目的私钥,第三个为设置的新口令,第四个为该私钥的公钥的证书链
FileOutputStream output=new FileOutputStream("another");
ks.store(output,storepass.toCharArray())将keystore对象内容写入新文件
八:JAVA程序检验别名和删除条目
FileInputStream in=new FileInputStream(".keystore");
KeyStore ks=KeyStore.getInstance("JKS");
ks.load(in,storepass.toCharArray());
ks.containsAlias("sage");检验条目是否在密钥库中,存在返回true
ks.deleteEntry("sage");删除别名对应的条目
FileOutputStream output=new FileOutputStream(".keystore");
ks.store(output,storepass.toCharArray())将keystore对象内容写入文件,条目删除成功
九:JAVA程序签发数字证书
(1)从密钥库中读取CA的证书
FileInputStream in=new FileInputStream(".keystore");
KeyStore ks=KeyStore.getInstance("JKS");
ks.load(in,storepass.toCharArray());
java.security.cert.Certificate c1=ks.getCertificate("caroot");
(2)从密钥库中读取CA的私钥
PrivateKey caprk=(PrivateKey)ks.getKey(alias,cakeypass.toCharArray());
(3)从CA的证书中提取签发者的信息
byte[] encod1=c1.getEncoded();提取CA证书的编码
X509CertImpl cimp1=new X509CertImpl(encod1);用该编码创建X509CertImpl类型对象
X509CertInfo cinfo1=(X509CertInfo)cimp1.get(X509CertImpl.NAME "." X509CertImpl.INFO);获取X509CertInfo对象
X500Name issuer=(X500Name)cinfo1.get(X509CertInfo.SUBJECT "." CertificateIssuerName.DN_NAME); 获取X509Name类型的签发者信息
(4)获取待签发的证书
CertificateFactory cf=CertificateFactory.getInstance("X.509");
FileInputStream in2=new FileInputStream("user.csr");
java.security.cert.Certificate c2=cf.generateCertificate(in);
(5)从待签发的证书中提取证书信息
byte [] encod2=c2.getEncoded();
X509CertImpl cimp2=new X509CertImpl(encod2);用该编码创建X509CertImpl类型对象
X509CertInfo cinfo2=(X509CertInfo)cimp2.get(X509CertImpl.NAME "." X509CertImpl.INFO);获取X509CertInfo对象
(6)设置新证书有效期
Date begindate=new Date(); 获取当前时间
Date enddate=new Date(begindate.getTime() 3000*24*60*60*1000L); 有效期为3000天
CertificateValidity cv=new CertificateValidity(begindate,enddate); 创建对象
cinfo2.set(X509CertInfo.VALIDITY,cv);设置有效期
(7)设置新证书序列号
int sn=(int)(begindate.getTime()/1000);以当前时间为序列号
CertificateSerialNumber csn=new CertificateSerialNumber(sn);
cinfo2.set(X509CertInfo.SERIAL_NUMBER,csn);
(8)设置新证书签发者
cinfo2.set(X509CertInfo.ISSUER "." CertificateIssuerName.DN_NAME,issuer);应用第三步的结果
(9)设置新证书签名算法信息
AlgorithmId algorithm=new AlgorithmId(AlgorithmId.md5WithRSAEncryption_oid);
cinfo2.set(CertificateAlgorithmId.NAME "." CertificateAlgorithmId.ALGORITHM,algorithm);
(10)创建证书并使用CA的私钥对其签名
X509CertImpl newcert=new X509CertImpl(cinfo2);
newcert.sign(caprk,"MD5WithRSA"); 使用CA私钥对其签名
(11)将新证书写入密钥库
ks.setCertificateEntry("lf_signed",newcert);
FileOutputStream out=new FileOutputStream("newstore");
ks.store(out,"newpass".toCharArray());这里是写入了新的密钥库,也可以使用第七条来增加条目
十:数字证书的检验
(1)验证证书的有效期
(a)获取X509Certificate类型对象
CertificateFactory cf=CertificateFactory.getInstance("X.509");
FileInputStream in1=new FileInputStream("aa.crt");
java.security.cert.Certificatec1=cf.generateCertificate(in1);
X509Certificate t=(X509Certificate)c1;
in2.close();
(b)获取日期
Date TimeNow=new Date();
(c)检验有效性
try{
t.checkValidity(TimeNow);
System.out.println("OK");
}catch(CertificateExpiredException e){//过期
System.out.println("Expired");
System.out.println(e.getMessage());
}catch((CertificateNotYetValidException e){ //尚未生效
System.out.println("Too early");
System.out.println(e.getMessage());}
(2)验证证书签名的有效性
(a)获取CA证书
CertificateFactory cf=CertificateFactory.getInstance("X.509");
FileInputStream in2=new FileInputStream("caroot.crt");
java.security.cert.Certificatecac=cf.generateCertificate(in2);
in2.close();
(c)获取CA的公钥
PublicKey pbk=cac.getPublicKey();
(b)获取待检验的证书(上步已经获取了,就是C1)
(c)检验证书
boolean pass=false;
try{
c1.verify(pbk);
pass=true;
}catch(Exception e){
pass=false;
System.out.println(e);
}
java,已知加密字符串,怎么生成cer文件?求代码package com.tgtbj.dsf.certhelper;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
import java.util.Date;
import javax.security.auth.x500.X500Principal;
import org.bouncycastle.x509.X509V3CertificateGenerator;
public class TT {
public static void genCertFile(String certPath, String password,
int keysize, String algorithm) throws Exception {
// 创建KeyStore
KeyStore store = KeyStore.getInstance("PKCS12");
store.load(null, null);
// 生成一对公私钥,这部分如果自己已经有了PublicKey,可以直接在下面使用,不用生成
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(keysize);
KeyPair keyPair = kpg.generateKeyPair();
// 这个字符串根据自己情况填
String issuer = "C=CN,ST=BJ,L=BJ,O=SSS,OU=SC,CN=SSS";
String subject = issuer;
X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
certGen.setIssuerDN(new X500Principal(issuer));
certGen.setNotBefore(new Date(System.currentTimeMillis() - 10 * 365
* 24 * 60 * 60 * 1000));
certGen.setNotAfter(new Date(System.currentTimeMillis()10 * 365 * 24
* 60 * 60 * 1000));
certGen.setSubjectDN(new X500Principal(subject));
certGen.setPublicKey(keyPair.getPublic());// 此处可直接传入线程的PublicKey
if (algorithm == null || algorithm.equals("")) {
certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
} else {
certGen.setSignatureAlgorithm(algorithm);
}
X509Certificate cert = certGen.generateX509Certificate(keyPair
.getPrivate());
// 私钥有现成的也可直接传入
store.setKeyEntry("alias", keyPair.getPrivate(),
password.toCharArray(), new Certificate[] { cert });
// 导出为 cer 证书
try {
FileOutputStream fos = new FileOutputStream(certPath".cer");
fos.write(cert.getEncoded());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (CertificateEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String args[]) throws Exception {
genCertFile("D:/opop1", "qwafrt", 1024, "SHA1WithRSA");
}
}
java rsa私钥加密java rsa私钥加密是什么?让我们一起来了解一下吧!
java rsa私钥加密是一种加密算法 。私钥加密算法是用私钥来进行加密与解密信息 。私钥加密也被称作对称加密,原因是加密与解密使用的秘钥是同一个 。
RSA加密需要注意的事项如下:
1. 首先产生公钥与私钥
2. 设计加密与解密的算法
3. 私钥加密的数据信息只能由公钥可以解密
4. 公钥加密的数据信息只能由私钥可以解密
实战演练,具体步骤如下:public class RsaCryptTools {private static final String CHARSET = "utf-8";private static final Base64.Decoder decoder64 = Base64.getDecoder();private static final Base64.Encoder encoder64 = Base64.getEncoder();/*** 生成公私钥* @param keySize* @return* @throws NoSuchAlgorithmException*/public static SecretKey generateSecretKey(int keySize) throws NoSuchAlgorithmException {//生成密钥对KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");keyGen.initialize(keySize, new SecureRandom());KeyPair pair = keyGen.generateKeyPair();PrivateKey privateKey = pair.getPrivate();PublicKey publicKey = pair.getPublic();//这里可以将密钥对保存到本地return new SecretKey(encoder64.encodeToString(publicKey.getEncoded()), encoder64.encodeToString(privateKey.getEncoded()));}/*** 私钥加密* @param data* @param privateInfoStr* @return* @throws IOException* @throws InvalidCipherTextException*/public static String encryptData(String data, String privateInfoStr) throws IOException, InvalidKeySpecException, NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException {Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");cipher.init(Cipher.ENCRYPT_MODE, getPrivateKey(privateInfoStr));return encoder64.encodeToString(cipher.doFinal(data.getBytes(CHARSET)));}/*** 公钥解密* @param data* @param publicInfoStr* @return*/public static String decryptData(String data, String publicInfoStr) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException {byte[] encryptDataBytes=decoder64.decode(data.getBytes(CHARSET));//解密Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");cipher.init(Cipher.DECRYPT_MODE, getPublicKey(publicInfoStr));return new String(cipher.doFinal(encryptDataBytes), CHARSET);}private static PublicKey getPublicKey(String base64PublicKey) throws NoSuchAlgorithmException, InvalidKeySpecException {X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(base64PublicKey.getBytes()));KeyFactory keyFactory = KeyFactory.getInstance("RSA");return keyFactory.generatePublic(keySpec);}private static PrivateKey getPrivateKey(String base64PrivateKey) throws NoSuchAlgorithmException, InvalidKeySpecException {PrivateKey privateKey = null;PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(base64PrivateKey.getBytes()));KeyFactory keyFactory = null;keyFactory = KeyFactory.getInstance("RSA");privateKey = keyFactory.generatePrivate(keySpec);return privateKey;}/*** 密钥实体* @author hank* @since 2020/2/28 0028 下午 16:27*/public static class SecretKey {/*** 公钥*/private String publicKey;/*** 私钥*/private String privateKey;public SecretKey(String publicKey, String privateKey) {this.publicKey = publicKey;this.privateKey = privateKey;}public String getPublicKey() {return publicKey;}public void setPublicKey(String publicKey) {this.publicKey = publicKey;}public String getPrivateKey() {return privateKey;}public void setPrivateKey(String privateKey) {this.privateKey = privateKey;}@Overridepublic String toString() {return "SecretKey{""publicKey='"publicKey'\''", privateKey='"privateKey'\'''}';}}private static void writeToFile(String path, byte[] key) throws IOException {File f = new File(path);f.getParentFile().mkdirs();try(FileOutputStream fos = new FileOutputStream(f)) {fos.write(key);fos.flush();}}public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, IOException, BadPaddingException, IllegalBlockSizeException, InvalidKeyException, InvalidKeySpecException {SecretKey secretKey = generateSecretKey(2048);System.out.println(secretKey);String enStr = encryptData("你好测试测试", secretKey.getPrivateKey());System.out.println(enStr);String deStr = decryptData(enStr, secretKey.getPublicKey());System.out.println(deStr);enStr = encryptData("你好测试测试hello", secretKey.getPrivateKey());System.out.println(enStr);deStr = decryptData(enStr, secretKey.getPublicKey());System.out.println(deStr);}}
【java公私钥生成代码 js生成公私钥】java公私钥生成代码的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于js生成公私钥、java公私钥生成代码的信息别忘了在本站进行查找喔 。
推荐阅读
- ios系统角色扮演游戏,苹果游戏角色扮演
- 电脑怎么设置cmos,电脑怎么设置cmyk色值
- 在js中dom,在js中dom是什么意思
- oracle如何测试包体 oracle如何测试package
- go语言插件大全,go语言 app
- 安卓手机如何打开手机定位,安卓手机怎样打开手机定位功能
- 苹果ios版本号,iphone版本
- 包含vb.net设计时的词条
- wordpress安装时候乱码,wordpress安装插件一直失败