数字签名问题,等待高手。。。。。。
xjspa 2005-04-17 10:02:16 本人根据网上一片文章《基于java的数字签名技术在电子政务中的应用》http://www.ahcit.com/200501/20050121.doc中的方法写的数字签名的例子,但不能读入要加密的源文件。请教高手。。。。。
import java.io.*;
import java.security.*;
import javax.crypto.*;
class encryption
{
public static void main(String[] args)
{
try
{
KeyPairGenerator DoublekeyGen=KeyPairGenerator.getInstance("RSA");
DoublekeyGen.initialize(1024);
KeyPair DoubleKey = DoublekeyGen.generateKeyPair();
PrivateKey priKey = DoubleKey.getPrivate();
PublicKey pubKey = DoubleKey.getPublic();
try
{
String fpubKey="d:\\pubKey.dat";
String fprivateKey="d:\\privateKey.dat";
File fpublic=new File(fpubKey);
File fprivate=new File(fprivateKey);
ObjectOutputStream outPub = new ObjectOutputStream(new FileOutputStream(fpublic));
ObjectOutputStream outPri =new ObjectOutputStream (new FileOutputStream(fprivate));
outPub.writeObject(pubKey);
outPri.writeObject(priKey);
outPub.close();
outPri.close();
}
catch(IOException e)
{
System.out.print(e.toString());
}
catch(SecurityException e)
{
System.out.print(e.toString());
}
KeyGenerator SinglekeyGen = KeyGenerator.getInstance("DES");
SinglekeyGen.init(56);
Key SingleKey = SinglekeyGen.generateKey();
try
{
/*以下的代码有问题,但我解决不了*/
ObjectInputStream ReadFile=new ObjectInputStream(new FileInputStream("d:\\privateKey.dat"));
byte[] ReadFilePlain=(byte[])ReadFile.readObject();
ReadFile.close();
/*将待传输的原始信息生成消息摘要MD_1*/
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
messageDigest.update(ReadFilePlain);
/*生成待传得摘要信息*/
byte[] MD_1 = messageDigest.digest();
/* 将消息摘要MD_1[]和对称密钥SingleKey合并到字节数组MK[]中,并用RSA算法中的私钥对该数组加密并保存在数组Rsa_sign[]中形成了数字签名*/
//for (int i=0;i<10;i++ )
int sl=SingleKey.getEncoded().length;
int ml=MD_1.length;
byte[] MK= new byte[ml+sl];
byte[] SK=SingleKey.getEncoded();
for (int i=0;i<ml;i++)
{
MK[i]=MD_1[i];
}
for(int i=0;i<sl;i++)
{
MK[ml+i]=SK[i];
}
System.out.print(MK.length);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, priKey);
byte[] Rsa_sign= (byte[])cipher.doFinal(MK);
/* 将待传输的信息用DES加密,并将加密后的数据保存在数组Des_info[]中*/
cipher=Cipher.getInstance("DES");
cipher.init(cipher.ENCRYPT_MODE,SingleKey);
byte[] Des_info = cipher.doFinal(ReadFilePlain);
try{
/*将需要传输的原文的密文和数字签名写到文件En_info.dat中,En_info.dat即为在网上传输的信息*/
ObjectOutputStream outPut = new ObjectOutputStream(new FileOutputStream("d:\\En_info.dat",true));
outPut.writeObject(Des_info);
outPut.writeObject(Rsa_sign);
outPut.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
catch(NoSuchAlgorithmException e)
{
System.out.println(e);
}
}
}