清单 6 显示了 generateSignature 方法:
清单 6. generateSignature 方法
public static byte[]
generateSignature(java.security.cert.X509Certificate signingCert,
byte[] messageContent)
throws Exception
{
try
{
PrivateKey ownerSigPrivateKey =
loadPrivateKeysFromPKCS12("C:/
temp/PKITS/signingExpPartner.p12","wpgindia")[0];
PKCS8EncodedKeySpec spec =
new PKCS8EncodedKeySpec(ownerSigPrivateKey.getEncoded());
KeyFactory kf =
KeyFactory.getInstance(ownerSigPrivateKey.getAlgorithm());
PrivateKey JCEPKey = kf.generatePrivate(spec);
SignedData signeddata = null;
byte[] encodedSignedData = null;
String digestAlgo = "sha1";
// SHA1/MD5 is the Message Digest Algo while RSA is the
Signature Algorithm ?? OK.
String signatureAlgorithm = "SHA1withRSA"; // default
if(digestAlgo != null || digestAlgo.equalsIgnoreCase("SHA1"))
signatureAlgorithm = "SHA1withRSA";
Data data = new Data();
data.setData(messageContent);
ContentInfo contentInfo = new ContentInfo(data);
java.security.cert.Certificate[] certs =
new java.security.cert.Certificate[1];
certs[0] = loadX509Certificate("C:/
temp/PKITS/signingExpPartner.der"); //signingCert;
CRL[] crls = null;
PKCSAttributes signedAttributes = null;
PKCSAttributes unsignedAttributes = null;
PrivateKey[] privateKeys = new PrivateKey[1];
privateKeys[0] = JCEPKey;
boolean signatureOnly =
false; //true; // Take false value NOT true, if you
want MessageDigest to be
generated for SingerInfo
// You need to generate SignedData Object with signatureOnly false and
signedAttributes = null || unsignedAttributes = null
// By doing this in SignerInfo(Retrieved from signedData) you will get:
// 1. MessageDigest
// 2. ContentType
// 3. SigningTime
signeddata =
new SignedData(certs,crls,contentInfo,signatureAlgorithm,privateKeys,
signedAttributes,unsignedAttributes,signatureOnly);
ContentInfo contentInfo2 = new ContentInfo(signeddata);
signeddata.removeContent();
encodedSignedData = contentInfo2.encode();
java.io.FileOutputStream fos =
new java.io.FileOutputStream("c:\\tempsig.txt");
fos.write((new String(encodedSignedData)).getBytes());
fos.close();
System.out.println("Generated Signature :"+new String(encodedSignedData));
return encodedSignedData;
}
catch ( Exception e )
{
e.printStackTrace();
throw e;
}
}
