导航:首页 > 编程语言 > java获取公钥

java获取公钥

发布时间:2022-09-18 03:11:57

java 如果随机生成秘钥对并获取

好像是,..这个你可以将公钥私钥放到一个MAP中 在这个MAP中初始化随即产生器然后生成密钥对 我也刚接触 还没看懂... //生成密钥
public static Map<String,Object> initKey(String seed) throws Exception{
KeyPairGenerator keygen = KeyPairGenerator.getInstance(ALGORITHM);
//初始化随机产生器
SecureRandom sr = new SecureRandom();
sr.setSeed(seed.getBytes());
keygen.initialize(KEY_SIZE,sr);

KeyPair keys = keygen.genKeyPair();

DSAPublicKey publicKey = (DSAPublicKey) keys.getPublic();
DSAPrivateKey privateKey = (DSAPrivateKey) keys.getPrivate();

Map<String,Object> map = new HashMap<String,Object>(2);
map.put(PUBLIC_KEY, publicKey);
map.put(PRIVATE_KEY, privateKey);

return map;
}

② java中如何得到公钥的key size

接你代码后面

Stringalgorithm=publickey.getAlgorithm();//获取算法
KeyFactorykeyFact=KeyFactory.getInstance(algorithm);
BigIntegerprime=null;
if("RSA".equals(algorithm)){//如果是RSA加密
RSAPublicKeySpeckeySpec=(RSAPublicKeySpec)keyFact.getKeySpec(publickey,RSAPublicKeySpec.class);
prime=keySpec.getMolus();
}elseif("DSA".equals(algorithm)){//如果是DSA加密
DSAPublicKeySpeckeySpec=(DSAPublicKeySpec)keyFact.getKeySpec(publickey,DSAPublicKeySpec.class);
prime=keySpec.getP();
}
intlen=prime.toString(2).length();//转换为二进制,获取公钥长度

③ 用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中的证书写入文件中,然后从该文件中读取证书信息
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;i<pkenc.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.Certificate c1=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(( 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.Certificate cac=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公钥加密,私钥解密,该怎么解决

RSA加密算法,是世界上第一个非对称加密算法,也是数论的第一个实际应用。它的算法如下:
1.找两个非常大的质数p和q(通常p和q都有155十进制位或都有512十进制位)并计算n=pq,k=(p-1)(q-1)。
2.将明文编码成整数M,保证M不小于0但是小于n。
3.任取一个整数e,保证e和k互质,而且e不小于0但是小于k。加密钥匙(称作公钥)是(e, n)。
4.找到一个整数d,使得ed除以k的余数是1(只要e和n满足上面条件,d肯定存在)。解密钥匙(称作密钥)是(d, n)。
加密过程: 加密后的编码C等于M的e次方除以n所得的余数。
解密过程: 解密后的编码N等于C的d次方除以n所得的余数。
只要e、d和n满足上面给定的条件。M等于N。

⑤ java代码怎么获取数字的证书那一串20位指纹

通过JAVA来读取数字证书的方法获取20位指纹:
CARead.java文件代码:
public class CARead extends JPanel {
private String CA_Name;
private String CA_ItemData[][] = new String[9][2];
private String[] columnNames = { "证书字段标记", "内容" };
public CARead(String CertName) {
CA_Name = CertName;
/* 三个Panel用来显示证书内容 */
JTabbedPane tabbedPane = new JTabbedPane();
JPanel panelNormal = new JPanel();
tabbedPane.addTab("普通信息", panelNormal);
JPanel panelAll = new JPanel();
panelAll.setLayout(new BorderLayout());
tabbedPane.addTab("所有信息", panelAll);
JPanel panelBase64 = new JPanel();
panelBase64.setLayout(new BorderLayout());
tabbedPane.addTab("Base64编码形式的信息", panelBase64);
/* 读取证书常规信息 */
Read_Normal(panelNormal);
/* 读取证书文件字符串表示内容 */
Read_Bin(panelAll);
/* 以Base64编码形式读取证书文件的信息 */
Read_Raw(panelBase64);
tabbedPane.setSelectedIndex(0);
setLayout(new GridLayout(1, 1));
add(tabbedPane);
}
private int Read_Normal(JPanel panel) {
String Field;
try {
CertificateFactory certificate_factory = CertificateFactory
.getInstance("X.509");
FileInputStream file_inputstream = new FileInputStream(CA_Name);
X509Certificate x509certificate = (X509Certificate) certificate_factory
.generateCertificate(file_inputstream);
Field = x509certificate.getType();
CA_ItemData[0][0] = "类型";
CA_ItemData[0][1] = Field;
Field = Integer.toString(x509certificate.getVersion());
CA_ItemData[1][0] = "版本";
CA_ItemData[1][1] = Field;
Field = x509certificate.getSubjectDN().getName();
CA_ItemData[2][0] = "标题";
CA_ItemData[2][1] = Field;
Field=x509certificate.getNotBefore().toString();//得到开始有效日期
CA_ItemData[3][0] = "开始有效日期";
CA_ItemData[3][1] = Field;
Field=x509certificate. getNotAfter().toString();//得到截止日期
CA_ItemData[4][0] = "截止日期";
CA_ItemData[4][1] = Field;
Field=x509certificate.getSerialNumber().toString(16);//得到序列号
CA_ItemData[5][0] = "序列号";
CA_ItemData[5][1] = Field;
Field=x509certificate.getIssuerDN().getName();//得到发行者名
CA_ItemData[6][0] = "发行者名";
CA_ItemData[6][1] = Field;
Field=x509certificate.getSigAlgName();//得到签名算法
CA_ItemData[7][0] = "签名算法";
CA_ItemData[7][1] = Field;
Field=x509certificate.getPublicKey().getAlgorithm();//得到公钥算法
CA_ItemData[8][0] = "公钥算法";
CA_ItemData[8][1] = Field;
//关闭输入流对象
file_inputstream.close();
final JTable table = new JTable(CA_ItemData, columnNames);
TableColumn tc = null; //表格列控制
tc = table.getColumnModel().getColumn(1);//得到表头
tc.setPreferredWidth(600);//设置宽度
panel.add(table);//增加到布局面板
} catch (Exception exception) {
exception.printStackTrace(); //异常捕获、
return -1;
}
return 0;
}
//读取二进制指纹文件
private int Read_Bin(JPanel panel) {
try {
FileInputStream file_inputstream = new FileInputStream(CA_Name);
DataInputStream data_inputstream = new DataInputStream(
file_inputstream);
CertificateFactory certificatefactory = CertificateFactory
.getInstance("X.509");
byte[] bytes = new byte[data_inputstream.available()];
data_inputstream.readFully(bytes);
ByteArrayInputStream s = new ByteArrayInputStream(bytes);
JEditorPane Cert_EditorPane;
Cert_EditorPane = new JEditorPane();
X509Certificate cert=null;
//遍历得到所有的证书属性
if (s.available() > 0)
{
cert = (X509Certificate) certificatefactory .generateCertificate(s);
Cert_EditorPane.setText(cert.toString());
}
Cert_EditorPane.disable();
JScrollPane edit_scroll = new JScrollPane(Cert_EditorPane);
panel.add(edit_scroll);
file_inputstream.close();
data_inputstream.close();
} catch (Exception exception) {
exception.printStackTrace();
return -1;
}
return 0;
}
private int Read_Raw(JPanel panel) {
try {
JEditorPane Cert_EditorPane = new JEditorPane();
StringBuffer strBuffer =new StringBuffer();
File inputFile = new File(CA_Name);
FileReader in = new FileReader(inputFile);
char[] buf = new char[2000];
int len = in.read(buf, 0, 2000);
for (int i = 1; i < len; i++) {
strBuffer.append(buf[i]);
}
in.close();
Cert_EditorPane.setText(strBuffer.toString());
Cert_EditorPane.disable();
JScrollPane edit_scroll = new JScrollPane(Cert_EditorPane);
panel.add(edit_scroll);
} catch (Exception exception) {
exception.printStackTrace();
return -1;
}
return 0;
}
}

⑥ java中如何得到公钥的key size

接你代码后面
String algorithm = publickey.getAlgorithm(); // 获取算法
KeyFactory keyFact = KeyFactory.getInstance(algorithm);
BigInteger prime = null;
if ("RSA".equals(algorithm)) { // 如果是RSA加密
RSAPublicKeySpec keySpec = (RSAPublicKeySpec)keyFact.getKeySpec(publickey, RSAPublicKeySpec.class);
prime = keySpec.getMolus();
} else if ("DSA".equals(algorithm)) { // 如果是DSA加密
DSAPublicKeySpec keySpec = (DSAPublicKeySpec)keyFact.getKeySpec(publickey, DSAPublicKeySpec.class);
prime = keySpec.getP();
}
int len = prime.toString(2).length(); // 转换为二进制,获取公钥长度

⑦ JAVA公钥加密,私钥解密,该怎么解决

一个比较简单的实现:一个三个类KeyGenerater生成公钥私钥对,Signaturer类使用私钥签名,SignProvider用公钥验证。公钥和私钥使用Base64加密Base64这个类也在博客里面
public class KeyGenerater {
private byte[] priKey;
private byte[] pubKey;
public void generater() {
try {
Java.security.KeyPairGenerator keygen = java.security.KeyPairGenerator
.getInstance("RSA");
SecureRandom secrand = new SecureRandom();
secrand.setSeed("syj".getBytes()); // 初始化随机产生器
keygen.initialize(1024, secrand);
KeyPair keys = keygen.genKeyPair();
PublicKey pubkey = keys.getPublic();
PrivateKey prikey = keys.getPrivate();
pubKey = Base64.encodeToByte(pubkey.getEncoded());
priKey = Base64.encodeToByte(prikey.getEncoded());
System.out.println("pubKey = " + new String(pubKey));
System.out.println("priKey = " + new String(priKey));
} catch (java.lang.Exception e) {
System.out.println("生成密钥对失败");
e.printStackTrace();
}
}
public byte[] getPriKey() {
return priKey;
}
public byte[] getPubKey() {
return pubKey;
}
}

public class Signaturer {
/**
*
* Description:数字签名
*
* @param priKeyText
* @param plainText
* @return
* @author 孙钰佳
* @since:2007-12-27 上午10:51:48
*/
public static byte[] sign(byte[] priKeyText, String plainText) {
try {
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64
.decode(priKeyText));
KeyFactory keyf = KeyFactory.getInstance("RSA");
PrivateKey prikey = keyf.generatePrivate(priPKCS8);
// 用私钥对信息生成数字签名
java.security.Signature signet = java.security.Signature
.getInstance("MD5withRSA");
signet.initSign(prikey);
signet.update(plainText.getBytes());
byte[] signed = Base64.encodeToByte(signet.sign());
return signed;
} catch (java.lang.Exception e) {
System.out.println("签名失败");
e.printStackTrace();
}
return null;
}
}
public class SignProvider {
private SignProvider() {
}
/**
*
* Description:校验数字签名,此方法不会抛出任务异常,成功返回true,失败返回false,要求全部参数不能为空
*
* @param pubKeyText
* 公钥,base64编码
* @param plainText
* 明文
* @param signTest
* 数字签名的密文,base64编码
* @return 校验成功返回true 失败返回false
* @author 孙钰佳
* @since:2007-12-27 上午09:33:55
*/
public static boolean verify(byte[] pubKeyText, String plainText,
byte[] signText) {
try {
// 解密由base64编码的公钥,并构造X509EncodedKeySpec对象
java.security.spec.X509EncodedKeySpec bobPubKeySpec = new java.security.spec.X509EncodedKeySpec(
Base64.decode(pubKeyText));
// RSA对称加密算法
java.security.KeyFactory keyFactory = java.security.KeyFactory
.getInstance("RSA");
// 取公钥匙对象
java.security.PublicKey pubKey = keyFactory
.generatePublic(bobPubKeySpec);
// 解密由base64编码的数字签名
byte[] signed = Base64.decode(signText);
java.security.Signature signatureChecker = java.security.Signature
.getInstance("MD5withRSA");
signatureChecker.initVerify(pubKey);
signatureChecker.update(plainText.getBytes());
// 验证签名是否正常
if (signatureChecker.verify(signed))
return true;
else
return false;
} catch (Throwable e) {
System.out.println("校验签名失败");
e.printStackTrace();
return false;
}
}
}

望采纳,谢谢。

⑧ Java通过RSA算法获取公私钥对 将公钥提供出去 如何获取字符串的公钥

直接将公匙BYTE数组转换为16进制的串啊
private static char hexTable[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
public static String toHexString(byte bytes[])
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++)
{
char chars[] = new char[2];
int d = (bytes[i] & 240) >> 4;
int m = bytes[i] & 15;
chars[0] = hexTable[d];
chars[1] = hexTable[m];
sb.append(chars);
}

return sb.toString();
}

⑨ JAVA 公钥与私钥的问题

这个公钥和私钥如果是非对称加密的算法,那么用公钥加密的话,就需要用私钥才能解密了。如果是对称加密的话,就用加密的公钥就可以解密了。

SSL加密通信的过程一般都是首先双方确认大家支持的加密方式,然后采用一种大家都支持的,然后的话,就先用非对称加密将公钥加密然后发给client,然后client解密获得公钥。之后的话,大家就可以用公钥进行对称加密了。

阅读全文

与java获取公钥相关的资料

热点内容
压缩因子定义 浏览:966
cd命令进不了c盘怎么办 浏览:212
药业公司招程序员吗 浏览:972
毛选pdf 浏览:657
linuxexecl函数 浏览:725
程序员异地恋结果 浏览:372
剖切的命令 浏览:226
干什么可以赚钱开我的世界服务器 浏览:288
php备案号 浏览:989
php视频水印 浏览:166
怎么追程序员的女生 浏览:487
空调外压缩机电容 浏览:79
怎么将安卓变成win 浏览:459
手机文件管理在哪儿新建文件夹 浏览:724
加密ts视频怎么合并 浏览:775
php如何写app接口 浏览:804
宇宙的琴弦pdf 浏览:396
js项目提成计算器程序员 浏览:944
pdf光子 浏览:834
自拍软件文件夹名称大全 浏览:328