    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.FileInputStream;
    048    import java.io.FileOutputStream;
    049    import java.io.InputStream;
    050    import java.io.InputStreamReader;
    051    import java.io.OutputStream;
    052    import java.io.PrintWriter;
    053    import java.math.BigInteger;
    054    import java.util.Arrays;
    055    import java.util.HashSet;
    056
    057    import iaik.pkcs.pkcs11.Mechanism;
    058    import iaik.pkcs.pkcs11.MechanismInfo;
    059    import iaik.pkcs.pkcs11.Module;
    060    import iaik.pkcs.pkcs11.Session;
    061    import iaik.pkcs.pkcs11.Token;
    062    import iaik.pkcs.pkcs11.TokenException;
    063    import iaik.pkcs.pkcs11.objects.DSAPrivateKey;
    064    import iaik.pkcs.pkcs11.objects.DSAPublicKey;
    065    import iaik.pkcs.pkcs11.objects.Key;
    066    import iaik.pkcs.pkcs11.objects.Object;
    067
    068
    069
    070    /**
    071     * Creates and verifies a signature on a token. The hash is calculated outside
    072     * the token. Notice that many tokens do not support verification. In this case
    073     * you will get an exception when the progrom tries to verify the signature
    074     * on the token.
    075     *
    076     * @author <a href="mailto:Karl.Scheibelhofer@iaik.at"> Karl Scheibelhofer </a>
    077     * @version 0.1
    078     * @invariants
    079     */
    080    public class DSASignAndVerify {
    081
    082      static BufferedReader input_;
    083
    084      static PrintWriter output_;
    085
    086      static {
    087        try {
    088          //output_ = new PrintWriter(new FileWriter("SignAndVerify_output.txt"), true);
    089          output_ = new PrintWriter(System.out, true);
    090          input_ = new BufferedReader(new InputStreamReader(System.in));
    091        } catch (Throwable thr) {
    092          thr.printStackTrace();
    093          output_ = new PrintWriter(System.out, true);
    094          input_ = new BufferedReader(new InputStreamReader(System.in));
    095       }
    096      }
    097
    098      public static void main(String[] args) {
    099        if ((args.length != 2) && (args.length != 3)) {
    100          printUsage();
    101          System.exit(1);
    102        }
    103
    104        try {
    105
    106            Module pkcs11Module = Module.getInstance(args[0]);
    107            pkcs11Module.initialize(null);
    108
    109            Token token = Util.selectToken(pkcs11Module, output_, input_);
    110            if (token == null) {
    111              output_.println("We have no token to proceed. Finished.");
    112              output_.flush();
    113              System.exit(0);
    114            }
    115
    116            // first check out what attributes of the keys we may set
    117            HashSet supportedMechanisms = new HashSet(Arrays.asList(token.getMechanismList()));
    118
    119            MechanismInfo signatureMechanismInfo;
    120            if (supportedMechanisms.contains(Mechanism.DSA_SHA1)) {
    121              signatureMechanismInfo = token.getMechanismInfo(Mechanism.DSA_SHA1);
    122            } else {
    123              signatureMechanismInfo = null;
    124              output_.println("The token does not support mechanism DSA_SHA1. Going to exit.");
    125              System.exit(0);
    126            }
    127
    128            if ((signatureMechanismInfo == null) || !signatureMechanismInfo.isSign()) {
    129              output_.println("The token does not support signing with mechanism DSA_SHA1. Going to exit.");
    130              System.exit(0);
    131            }
    132
    133            Session session = Util.openAuthorizedSession(token, Token.SessionReadWriteBehavior.RO_SESSION, output_, input_);
    134
    135            output_.println("################################################################################");
    136            output_.println("find private signature key");
    137            DSAPrivateKey templateSignatureKey = new DSAPrivateKey();
    138            templateSignatureKey.getSign().setBooleanValue(Boolean.TRUE);
    139
    140            KeyAndCertificate selectedSignatureKeyAndCertificate =
    141                Util.selectKeyAndCertificate(session, templateSignatureKey, output_, input_);
    142            if (selectedSignatureKeyAndCertificate == null) {
    143              output_.println("We have no signature key to proceed. Finished.");
    144              output_.flush();
    145              System.exit(0);
    146            }
    147            Key signatureKey = selectedSignatureKeyAndCertificate.getKey();
    148            output_.println("################################################################################");
    149
    150
    151            output_.println("################################################################################");
    152            output_.println("signing data from file: " + args[1]);
    153
    154            InputStream dataInputStream = new FileInputStream(args[1]);
    155
    156            //be sure that your token can process the specified mechanism
    157            Mechanism signatureMechanism = Mechanism.DSA_SHA1;
    158            // initialize for signing
    159            session.signInit(signatureMechanism, signatureKey);
    160
    161            byte[] dataBuffer = new byte[1024];
    162            byte[] helpBuffer;
    163            int bytesRead;
    164
    165            // feed all data from the input stream to the message digest
    166            while ((bytesRead = dataInputStream.read(dataBuffer)) >= 0) {
    167              helpBuffer = new byte[bytesRead]; // we need a buffer that only holds what to send for signing
    168              System.arraycopy(dataBuffer, 0, helpBuffer, 0, bytesRead);
    169              session.signUpdate(helpBuffer);
    170              Arrays.fill(helpBuffer, (byte) 0); // ensure that no data is left in the memory
    171            }
    172
    173            byte[] signatureValue = session.signFinal();
    174
    175            Arrays.fill(dataBuffer, (byte) 0); // ensure that no data is left in the memory
    176
    177            output_.println("The siganture value is: " + new BigInteger(1, signatureValue).toString(16));
    178
    179            if (args.length == 3) {
    180              output_.println("Writing signature to file: " + args[2]);
    181
    182              OutputStream signatureOutput = new FileOutputStream(args[2]);
    183              signatureOutput.write(signatureValue);
    184              signatureOutput.flush();
    185              signatureOutput.close();
    186            }
    187
    188            output_.println("################################################################################");
    189
    190
    191            if ((signatureMechanismInfo == null) || !signatureMechanismInfo.isVerify()) {
    192              output_.println("The token does not support verification with mechanism RSA_PKCS. Going to exit.");
    193              System.exit(0);
    194            }
    195
    196            output_.println("################################################################################");
    197            output_.println("find public verification key");
    198            DSAPublicKey templateVerificationKey = new DSAPublicKey();
    199            templateVerificationKey.getVerify().setBooleanValue(Boolean.TRUE);
    200            // we search for a public key with the same ID
    201            templateVerificationKey.getId().setByteArrayValue(signatureKey.getId().getByteArrayValue());
    202
    203            session.findObjectsInit(templateVerificationKey);
    204
    205            Object[] foundVerificationKeyObjects = session.findObjects(1); // find first
    206
    207            DSAPublicKey verificationKey = null;
    208            if (foundVerificationKeyObjects.length > 0) {
    209              verificationKey = (DSAPublicKey) foundVerificationKeyObjects[0];
    210              output_.println("________________________________________________________________________________");
    211              output_.println(verificationKey);
    212              output_.println("________________________________________________________________________________");
    213           } else {
    214              output_.println("No matching public key found!");
    215              System.exit(0);
    216            }
    217            session.findObjectsFinal();
    218
    219            output_.println("################################################################################");
    220
    221
    222            output_.println("################################################################################");
    223            output_.println("verifying signature");
    224
    225            dataInputStream = new FileInputStream(args[1]);
    226
    227            // feed all data from the input stream to the message digest
    228            while ((bytesRead = dataInputStream.read(dataBuffer)) >= 0) {
    229              helpBuffer = new byte[bytesRead]; // we need a buffer that only holds what to send for signing
    230              System.arraycopy(dataBuffer, 0, helpBuffer, 0, bytesRead);
    231              session.signUpdate(helpBuffer);
    232              Arrays.fill(helpBuffer, (byte) 0); // ensure that no data is left in the memory
    233            }
    234
    235            //be sure that your token can process the specified mechanism
    236            Mechanism verificationMechanism = Mechanism.DSA_SHA1;
    237            // initialize for signing
    238            session.verifyInit(verificationMechanism, verificationKey);
    239
    240            try {
    241              session.verifyFinal(signatureValue); // throws an exception upon unsuccessful verification
    242              output_.println("Verified the signature successfully");
    243            } catch (TokenException ex) {
    244              output_.println("Verification FAILED: " + ex.getMessage());
    245            }
    246
    247            output_.println("################################################################################");
    248
    249
    250            session.closeSession();
    251            pkcs11Module.finalize(null);
    252
    253        } catch (Throwable thr) {
    254          thr.printStackTrace();
    255        } finally {
    256          output_.close();
    257        }
    258      }
    259
    260      public static void printUsage() {
    261        output_.println("Usage: DSASignAndVerify <PKCS#11 module> <file to be signed> [<signature value file>]");
    262        output_.println(" e.g.: DSASignAndVerify pk2priv.dll data.dat signature.bin");
    263        output_.println("The given DLL must be in the search path of the system.");
    264      }
    265
    266    }