001 /* Copyright (c) 2002 Graz University of Technology. All rights reserved. 002 * 003 * Redistribution and use in source and binary forms, with or without 004 * modification, are permitted provided that the following conditions are met: 005 * 006 * 1. Redistributions of source code must retain the above copyright notice, 007 * this list of conditions and the following disclaimer. 008 * 009 * 2. Redistributions in binary form must reproduce the above copyright notice, 010 * this list of conditions and the following disclaimer in the documentation 011 * and/or other materials provided with the distribution. 012 * 013 * 3. The end-user documentation included with the redistribution, if any, must 014 * include the following acknowledgment: 015 * 016 * "This product includes software developed by IAIK of Graz University of 017 * Technology." 018 * 019 * Alternately, this acknowledgment may appear in the software itself, if 020 * and wherever such third-party acknowledgments normally appear. 021 * 022 * 4. The names "Graz University of Technology" and "IAIK of Graz University of 023 * Technology" must not be used to endorse or promote products derived from 024 * this software without prior written permission. 025 * 026 * 5. Products derived from this software may not be called 027 * "IAIK PKCS Wrapper", nor may "IAIK" appear in their name, without prior 028 * written permission of Graz University of Technology. 029 * 030 * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED 031 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 032 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 033 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE LICENSOR BE 034 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, 035 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 036 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 037 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 038 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 039 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 040 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 041 * POSSIBILITY OF SUCH DAMAGE. 042 */ 043 044 package demo.pkcs.pkcs11; 045 046 import java.io.BufferedReader; 047 import java.io.ByteArrayInputStream; 048 import java.io.FileInputStream; 049 import java.io.FileOutputStream; 050 import java.io.InputStream; 051 import java.io.InputStreamReader; 052 import java.io.OutputStream; 053 import java.io.PrintWriter; 054 import java.math.BigInteger; 055 import java.security.MessageDigest; 056 import java.security.Signature; 057 import java.security.SignatureException; 058 import java.security.cert.CertificateFactory; 059 import java.security.cert.X509Certificate; 060 import java.util.Hashtable; 061 062 import iaik.asn1.structures.AlgorithmID; 063 import iaik.pkcs.pkcs11.Mechanism; 064 import iaik.pkcs.pkcs11.MechanismInfo; 065 import iaik.pkcs.pkcs11.Module; 066 import iaik.pkcs.pkcs11.Session; 067 import iaik.pkcs.pkcs11.Token; 068 import iaik.pkcs.pkcs11.TokenException; 069 import iaik.pkcs.pkcs11.objects.Key; 070 import iaik.pkcs.pkcs11.objects.Object; 071 import iaik.pkcs.pkcs11.objects.RSAPrivateKey; 072 import iaik.pkcs.pkcs11.objects.RSAPublicKey; 073 import iaik.pkcs.pkcs7.DigestInfo; 074 075 076 077 /** 078 * Creates and verifies a signature on a token. The hash is calculated outside 079 * the token. Notice that many tokens do not support verification. In this case 080 * you will get an exception when the program tries to verify the signature 081 * on the token. 082 * 083 * @author <a href="mailto:Karl.Scheibelhofer@iaik.at"> Karl Scheibelhofer </a> 084 * @version 0.1 085 * @invariants 086 */ 087 public class SignAndVerify { 088 089 static BufferedReader input_; 090 091 static PrintWriter output_; 092 093 static { 094 try { 095 //output_ = new PrintWriter(new FileWriter("SignAndVerify_output.txt"), true); 096 output_ = new PrintWriter(System.out, true); 097 input_ = new BufferedReader(new InputStreamReader(System.in)); 098 } catch (Throwable thr) { 099 thr.printStackTrace(); 100 output_ = new PrintWriter(System.out, true); 101 input_ = new BufferedReader(new InputStreamReader(System.in)); 102 } 103 } 104 105 public static void main(String[] args) { 106 if ((args.length != 2) && (args.length != 3)) { 107 printUsage(); 108 System.exit(1); 109 } 110 111 try { 112 113 Module pkcs11Module = Module.getInstance(args[0]); 114 pkcs11Module.initialize(null); 115 116 Token token = Util.selectToken(pkcs11Module, output_, input_); 117 if (token == null) { 118 output_.println("We have no token to proceed. Finished."); 119 output_.flush(); 120 System.exit(0); 121 } 122 123 // first check out what attributes of the keys we may set 124 Mechanism[] mechanisms = token.getMechanismList(); 125 Hashtable supportedMechanisms = new Hashtable(mechanisms.length); 126 for (int i = 0; i < mechanisms.length; i++) { 127 supportedMechanisms.put(mechanisms[i], mechanisms[i]); 128 } 129 130 MechanismInfo signatureMechanismInfo; 131 if (supportedMechanisms.contains(Mechanism.RSA_PKCS)) { 132 signatureMechanismInfo = token.getMechanismInfo(Mechanism.RSA_PKCS); 133 } else { 134 signatureMechanismInfo = null; 135 output_.println("The token does not support mechanism RSA_PKCS. Going to exit."); 136 System.exit(0); 137 } 138 139 if ((signatureMechanismInfo == null) || !signatureMechanismInfo.isSign()) { 140 output_.println("The token does not support signing with mechanism RSA_PKCS. Going to exit."); 141 System.exit(0); 142 } 143 144 Session session = Util.openAuthorizedSession(token, Token.SessionReadWriteBehavior.RO_SESSION, output_, input_); 145 146 output_.println("################################################################################"); 147 output_.println("find private signature key"); 148 RSAPrivateKey templateSignatureKey = new RSAPrivateKey(); 149 templateSignatureKey.getSign().setBooleanValue(Boolean.TRUE); 150 151 KeyAndCertificate selectedSignatureKeyAndCertificate = 152 Util.selectKeyAndCertificate(session, templateSignatureKey, output_, input_); 153 if (selectedSignatureKeyAndCertificate == null) { 154 output_.println("We have no signature key to proceed. Finished."); 155 output_.flush(); 156 System.exit(0); 157 } 158 Key signatureKey = selectedSignatureKeyAndCertificate.getKey(); 159 output_.println("################################################################################"); 160 161 162 output_.println("################################################################################"); 163 output_.println("signing data from file: " + args[1]); 164 165 InputStream dataInputStream = new FileInputStream(args[1]); 166 167 // we do digesting outside the card, because some cards do not support on-card hashing 168 MessageDigest digestEngine = MessageDigest.getInstance("SHA-1"); 169 170 //be sure that your token can process the specified mechanism 171 Mechanism signatureMechanism = Mechanism.RSA_PKCS; 172 // initialize for signing 173 session.signInit(signatureMechanism, signatureKey); 174 175 byte[] dataBuffer = new byte[1024]; 176 //byte[] helpBuffer; 177 int bytesRead; 178 179 // feed all data from the input stream to the message digest 180 while ((bytesRead = dataInputStream.read(dataBuffer)) >= 0) { 181 //helpBuffer = new byte[bytesRead]; // we need a buffer that only holds what to send for signing 182 //System.arraycopy(dataBuffer, 0, helpBuffer, 0, bytesRead); 183 //session.signUpdate(helpBuffer); 184 //Arrays.fill(helpBuffer, (byte) 0); // ensure that no data is left in the memory 185 digestEngine.update(dataBuffer, 0, bytesRead); 186 } 187 byte[] digest = digestEngine.digest(); 188 189 // according to PKCS#11 building the DigestInfo structure must be done off-card 190 DigestInfo digestInfoObject = new DigestInfo(AlgorithmID.sha1, digest); 191 192 byte[] digestInfo = digestInfoObject.toByteArray(); 193 194 byte[] signatureValue = session.sign(digestInfo); 195 196 //Arrays.fill(dataBuffer, (byte) 0); // ensure that no data is left in the memory 197 198 output_.println("The siganture value is: " + new BigInteger(1, signatureValue).toString(16)); 199 200 if (args.length == 3) { 201 output_.println("Writing signature to file: " + args[2]); 202 203 OutputStream signatureOutput = new FileOutputStream(args[2]); 204 signatureOutput.write(signatureValue); 205 signatureOutput.flush(); 206 signatureOutput.close(); 207 } 208 209 output_.println("################################################################################"); 210 211 212 if ((signatureMechanismInfo == null) || !signatureMechanismInfo.isVerify()) { 213 output_.println("The token does not support verification with mechanism RSA_PKCS. Going to exit."); 214 System.exit(0); 215 } 216 217 boolean verifyInSoftware; 218 output_.println("################################################################################"); 219 output_.println("find public verification key"); 220 RSAPublicKey templateVerificationKey = new RSAPublicKey(); 221 templateVerificationKey.getVerify().setBooleanValue(Boolean.TRUE); 222 // we search for a public key with the same ID 223 templateVerificationKey.getId().setByteArrayValue(signatureKey.getId().getByteArrayValue()); 224 225 session.findObjectsInit(templateVerificationKey); 226 227 Object[] foundVerificationKeyObjects = session.findObjects(1); // find first 228 229 RSAPublicKey verificationKey = null; 230 if (foundVerificationKeyObjects.length > 0) { 231 verificationKey = (RSAPublicKey) foundVerificationKeyObjects[0]; 232 output_.println("________________________________________________________________________________"); 233 output_.println(verificationKey); 234 output_.println("________________________________________________________________________________"); 235 verifyInSoftware = false; 236 } else { 237 if (selectedSignatureKeyAndCertificate.getCertificate() != null) { 238 output_.println("No matching public key found! Will verify in software."); 239 } else { 240 output_.println("No matching public key found and no certificate found! Going to exit."); 241 System.exit(0); 242 } 243 verifyInSoftware = true; 244 } 245 session.findObjectsFinal(); 246 247 output_.println("################################################################################"); 248 249 250 output_.println("################################################################################"); 251 if (verifyInSoftware) { 252 output_.println("verifying signature in software"); 253 CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); 254 byte[] encodedCertificate = 255 selectedSignatureKeyAndCertificate.getCertificate().getValue().getByteArrayValue(); 256 X509Certificate certificate = (X509Certificate) certificateFactory.generateCertificate( 257 new ByteArrayInputStream(encodedCertificate)); 258 Signature signatureEngine = Signature.getInstance("SHA1withRSA"); 259 260 signatureEngine.initVerify(certificate.getPublicKey()); 261 dataInputStream = new FileInputStream(args[1]); 262 // feed all data from the input stream to the message digest 263 while ((bytesRead = dataInputStream.read(dataBuffer)) >= 0) { 264 //helpBuffer = new byte[bytesRead]; // we need a buffer that only holds what to send for signing 265 //System.arraycopy(dataBuffer, 0, helpBuffer, 0, bytesRead); 266 //session.signUpdate(helpBuffer); 267 //Arrays.fill(helpBuffer, (byte) 0); // ensure that no data is left in the memory 268 signatureEngine.update(dataBuffer, 0, bytesRead); 269 } 270 271 try { 272 if (signatureEngine.verify(signatureValue)) { 273 output_.println("Verified the signature successfully"); 274 } else { 275 output_.println("Signature Invalid." ); 276 } 277 } catch (SignatureException ex) { 278 output_.println("Verification FAILED: " + ex.getMessage()); 279 } 280 } else { 281 output_.println("verifying signature on token"); 282 283 dataInputStream = new FileInputStream(args[1]); 284 285 // feed all data from the input stream to the message digest 286 while ((bytesRead = dataInputStream.read(dataBuffer)) >= 0) { 287 //helpBuffer = new byte[bytesRead]; // we need a buffer that only holds what to send for signing 288 //System.arraycopy(dataBuffer, 0, helpBuffer, 0, bytesRead); 289 //session.signUpdate(helpBuffer); 290 //Arrays.fill(helpBuffer, (byte) 0); // ensure that no data is left in the memory 291 digestEngine.update(dataBuffer, 0, bytesRead); 292 } 293 digest = digestEngine.digest(); 294 295 // according to PKCS#11 building the DigestInfo structure must be done off-card 296 digestInfoObject = new DigestInfo(AlgorithmID.sha1, digest); 297 298 digestInfo = digestInfoObject.toByteArray(); 299 300 //be sure that your token can process the specified mechanism 301 Mechanism verificationMechanism = Mechanism.RSA_PKCS; 302 // initialize for signing 303 session.verifyInit(verificationMechanism, verificationKey); 304 305 try { 306 session.verify(digestInfo, signatureValue); // throws an exception upon unsuccessful verification 307 output_.println("Verified the signature successfully"); 308 } catch (TokenException ex) { 309 output_.println("Verification FAILED: " + ex.getMessage()); 310 } 311 } 312 313 output_.println("################################################################################"); 314 315 session.closeSession(); 316 pkcs11Module.finalize(null); 317 318 } catch (Throwable thr) { 319 thr.printStackTrace(); 320 } finally { 321 output_.close(); 322 } 323 } 324 325 public static void printUsage() { 326 output_.println("Usage: SignAndVerify <PKCS#11 module> <file to be signed> [<signature value file>]"); 327 output_.println(" e.g.: SignAndVerify pk2priv.dll data.dat signature.bin"); 328 output_.println("The given DLL must be in the search path of the system."); 329 } 330 331 }