站内搜索: 请输入搜索关键词

当前页面: 开发资料首页Java 专题BouncyCastle JCE实践(六)

BouncyCastle JCE实践(六)

摘要: BouncyCastle JCE实践(六)

签名的实现过程
1)读取自己的私钥
对于自己的私钥文件,要用File类来声明。读取时,将用FileInputStream格式来作为输入流。而读出的密钥是字节数组,所以应该将读出的密钥用ByteArrayOutStream来保存,再用toByteArray格式来将它转化为字节数组。
生成签名要使用自己的私钥,而私钥使用PKCS8#编码。所以我们还要将字节数组转化为PKCS8#编码形式。实现方法如下:
PKCS8EncodedKeySpec keyspec=new PKCS8EncodedKeySpec(keybytes);
KeyFactory keyfactory=KeyFactory.getInstance("RSA");
syprivatekey=keyfactory.generatePrivate(keyspec);
其中keybytes是从原文中读出的字节数组形式的密钥。用KeyFactory对象的实例化方法来指定算法,并用generatePrivate方法产生PKCS8#编码的私钥。
2)从对话框中取得要签名的文件
该步骤的实现比较简单,不做过多说明。
3)将文件内容读取为字节数组格式
因为签名时Signature类的Update()方法的参数是字节数组形式,所以要求
先将原文读为字节数组。并且,在此处可以获得原文的内容长度。
4)生成签名
按照前面的描述,先用Signature类的getInstance()方法指定MD5WithRSA
算法,然后用前面得到的私钥作为参数调用initSign()方法来初始化,最后用原文作为参数调用update()方法来传送数据,用字节数组形式的私钥作为参数调用Sign()方法来产生签名。
将生成的签名按照前面设计的文件格式写入文件流中,就完成了签名的全部工作。签名的实现过程可用下面的图来表示:
图 数字签名过程
代码实现如下:
//读取私钥
PrivateKey syprivatekey=null;
File syfile=new File("c:\\安全文件\\"+misClass.username+"\\非对称\\本人公私钥\\yhb.private");
try
{
FileInputStream fis=new FileInputStream(syfile);
ByteArrayOutputStream baos=new ByteArrayOutputStream();
int thebyte=0;
while((thebyte=fis.read())!=-1)
{baos.write(thebyte); }
fis.close();
byte[] keybytes=baos.toByteArray();
baos.close();
PKCS8EncodedKeySpec keyspec=new PKCS8EncodedKeySpec(keybytes);
KeyFactory keyfactory=KeyFactory.getInstance("RSA");
syprivatekey=keyfactory.generatePrivate(keyspec); }
catch(Exception e9) {
System.out.print("error when read the rsa private key");
System.exit(0);
} //从对话框中取得要签名的文件
File file=new File(dirstring1,string1);
String filename=file.getName();
//首先将文件读为byte[]对象
int len=(int)file.length();
if(len>100000000)
{System.out.println("the file length is too long!");
System.exit(0); }
byte[] inbuf=new byte[len];
try{
FileInputStream instream=new FileInputStream(file);
int inbytes=instream.available();
//inbuf[]=new byte[inbytes];
int bytesread=instream.read(inbuf,0,inbytes);
instream.close();
//System.out.println(inbuf); }
catch(Exception eq2) {
System.out.println("error when change the file to byte[]");
System.exit(0);
}
//签名的具体过程
try{
//byte[] signaturebytes=new byte[150];
Signature sig=Signature.getInstance("MD5WithRSA");
sig.initSign(syprivatekey);
sig.update(inbuf);
byte[] signaturebytes=sig.sign();
//写入对象流中
DataOutputStream outfile=new DataOutputStream(new FileOutputStream(
"c:\\安全文件\\文件\\"+filename+".yhb3"));
outfile.writeInt(signaturebytes.length);
outfile.write(signaturebytes);
outfile.writeInt(len);
outfile.write(inbuf);
outfile.close();
}
catch(Exception eh3)
{ System.out.println("error when generate the outfile");
System.exit(0); }
↑返回目录
前一篇: BouncyCastle JCE实践(三)
后一篇: Borland JBuilder 与 JBoss 的集成和配置