① 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解密獲得公鑰。之後的話,大家就可以用公鑰進行對稱加密了。