ALG_RSA_SHA_PKCS1

Hi guys,
I have a question that seems to be rather critical, but I couldn't
find any mention of it in the archive here:
In the Java card API spec of Sigature class,
ALG_RSA_SHA_PKCS1 is defined to expect the SHA hash, the algorithm
will then pad it according to PKCS1 and generate the signature.
However, the Sign method definition seems to contradict this by
saying "generate signature of all/last input data", which suggest
that it performs the hashing on the input data also (in the case of
all). This applies to all other algorithms (mixture of hash and
padding spec).
Can someone tell me which interpretation is correct as we have encoutered
card vendors who implemented both ways.
dwen

Usually Signature.ALG_RSA_SHA_PKCS1 does the complete signature generation. This means it expects the plain message to be signed as input data (not the digest! - the API spec is a bit misleading) and then does all the operations indicated in it's name: SHA1 + PKCS1 padding + RSA modexp
If you want to split these operations (e.g. often you calculate the SHA digest off-card) the you can use one of the Cipher engines, for instance, Cipher.ALG_RSA_PKCS1 or Cipher.ALG_RSA_NOPAD.

Similar Messages

  • ALG_RSA_SHA_PKCS1  with  cyberflex 64k

    Hello,
    I've tested with success ALG_RSA_PKCS1 , on gemalto cyberflex 32K and even 64k
    here is my crypt fonction :
    private void encryptRSA(APDU apdu)
              byte a[] = apdu.getBuffer();
              short byteRead = (short) (apdu.setIncomingAndReceive());
              cipherRSA.init(rsa_PrivateCrtKey, Cipher.MODE_ENCRYPT);
              short cyphertext = cipherRSA.doFinal(a, (short) dataOffset, byteRead, a, (short) dataOffset);
              // Send results
              apdu.setOutgoing();
              apdu.setOutgoingLength((short) cyphertext);
              apdu.sendBytesLong(a, (short) dataOffset, (short) cyphertext);
         }but when i couple it with sha1 , i've got a bad error with this code quite similar :
    private void signDocs(APDU apdu) {
              byte apduBuffer[] = apdu.getBuffer();              
             short byteRead = (short) (apdu.setIncomingAndReceive());       
         // create signature
             sig.init(rsa_PrivateCrtKey, Signature.MODE_SIGN);
         byte[] sigResult = null;
             short size = sig.sign(apdluBuffer, (short) dataOffset, byteRead, sigResult, (short) dataOffset);
             apdu.setOutgoing();
             apdu.setOutgoingLength((short) size);
             apdu.sendBytesLong(sigResult, (short) dataOffset, (short) size);
    i followed everything like in the doc 2.2.1
    the two corresponding lines at the beginning are :
    public Signature sig=null;
    sig = Signature.getInstance(Signature.ALG_RSA_SHA_PKCS1,false);
    the compilation and the load of the cardlet is good but when i want to sign :-----------> error 6F00
    I'm surprised because RSA without SHA1 works very well , i arrive to export the public key and use it on the pc....
    and according to the spec of my 64k card it is compatible with sha1 :
    [http://scardshop.com/boutique/fiche_produit.cfm?ref=CPCB64P&type=2&code_lg=lg_fr&num=11 ]
    kind regards,
    Marc

    Hello,
    Some news,
    when i use the public key in the card like this , it works:
    private void signDocs(APDU apdu) {
              byte apduBuffer[] = apdu.getBuffer();              
             short byteRead = (short) (apdu.setIncomingAndReceive());       
         // create signature
             sig.init(rsa_PublicKey, Signature.MODE_SIGN);
         byte[]  sigResult =new byte[(short)128];
             short size = sig.sign(apduBuffer, (short) 0, byteRead, apduBuffer, (short) 0);
             apdu.setOutgoing();
             apdu.setOutgoingLength((short) size);
             apdu.sendBytesLong(apduBuffer, (short) 0, (short) size);
         }when i say it works, it returns a 128 byte array an i haven't verify the signature yet
    but that wants to say i will have to export the private key if i wants to decrypt it on the pc
    and i will never have to export my public key.... ( wich will be considerated like a private...)
    will it work ?
    i've found another solution :
    http://forums.sun.com/thread.jspa?forumID=23&threadID=5240359
    but i would prefer my solution
    help me please, i'm very limited in time,
    (ps : sorry for my bad english)
    kind regards,
    Marc

  • SecurityException while using Signature object in processToolkit

    Hello,
    I'm stuck on problem when trying to sign some data with RSA algorithm.
    following code initializes RSA keys and Signature object in class constructor:
    public class cryptoTest extends javacard.framework.Applet implements ToolkitInterface, ToolkitConstants {
    private RSAPublicKey rsa_PublicKey;
    private RSAPrivateKey rsa_PrivateKey;
    private Signature sigRSA;
    public cryptoTest() {
              try {
                   KeyPair rsa_KeyPair = new KeyPair( KeyPair.ALG_RSA, KeyBuilder.LENGTH_RSA_512 );
                   rsa_KeyPair.genKeyPair();
                   rsa_PublicKey = (RSAPublicKey) rsa_KeyPair.getPublic();
                   rsa_PrivateKey = (RSAPrivateKey) rsa_KeyPair.getPrivate();
                   sigRSA = Signature.getInstance(Signature.ALG_RSA_SHA_PKCS1, false);
              }catch(Exception e) {
                   cryptoInitialized = false;
    }then I need to sign a data when user selects one of the toolkit menu items, so the following goes into menu item handler:
                   byte[] enc = JCSystem.makeTransientByteArray((short)65, JCSystem.CLEAR_ON_RESET);
                   byte[] data = JCSystem.makeTransientByteArray((short)8, JCSystem.CLEAR_ON_RESET);
    // FILL "data" object with correct data
                   try {
                        sigRSa.init(rsa_PrivateKey, Signature.MODE_SIGN);
                        sigRSA.sign(data, (short)0, (short)8, enc, (short)0);
                   }catch(SecurityException e) {
                                // process exception
    .............but when I choose this menu item, SecurityException occurs on signRSA.sign(....) line. if I move this code into process() method and execute it via APDU command from card reader, everything works fine, I'll get signed data. but same code from menu handler causes an exception. I'm quite sure the problem is very simple, but I'm missing something very fundamental in SIMToolKit.
    Thanks for help and best regards,
    Irakli,

    Change this:
    sigRSA = Signature.getInstance(Signature.ALG_RSA_SHA_PKCS1, false);To this:
    sigRSA = Signature.getInstance(Signature.ALG_RSA_SHA_PKCS1, true);

  • Problem signing data

    Hi,
    I have the following code snippet. The signing of a 256 byte(2048 bit input stream) fails. The exception that I catch is ILLEGAL USE. I am just straight away passing the input stream for signing without any preprocessing of the i/p steam.
    However, the signing fails. Anybody, who is familiar with this problem please help.
    The code:
    try{
              privKey = (RSAPrivateKey) KeyBuilder.buildKey(KeyBuilder.TYPE_RSA_PRIVATE, keySize, false);
         privKey.setExponent(privExponent, (short)0, (short)256);
         privKey.setModulus(privModulus, (short)0, (short)256);
         catch(CryptoException e){
    if (e.getReason() == CryptoException.NO_SUCH_ALGORITHM)
    ISOException.throwIt(ALGO_ERROR);
              else
    if (e.getReason() == CryptoException.ILLEGAL_VALUE)
    ISOException.throwIt(ILL_VAL);
              else
    ISOException.throwIt(KEYGEN_FAILED);
         try{
         signature = Signature.getInstance(Signature.ALG_RSA_SHA_PKCS1, false);
              signature.init(privKey, Signature.MODE_SIGN);
              }catch(CryptoException e)
                   ISOException.throwIt(SIGNINIT_ERROR);
         try{
              outputlen = signature.sign(buf, (short) 0, (short)length, outbuf, (short) 0);
              }catch(CryptoException e)
              if (e.getReason() == CryptoException.UNINITIALIZED_KEY)
    ISOException.throwIt(ALGO_ERROR);
              else
    if (e.getReason() == CryptoException.ILLEGAL_USE)
    ISOException.throwIt(ILL_VAL);
              else
    ISOException.throwIt(SIGNATURE_FAILED);
              }

    Sorry, my previous post was a little inaccurate. The limitation is on RSA encryption. For a signature, your data is hashed (using SHA1 in this instance) and this hash is then encrypted with the private key.
    What happens if you try to sign a few bytes (say 8)? Your code looks fine to me. I have tried something similar myself and it works. I use CRT keys as my card does not support non-crt private keys (that could even be part of the problem but I would expect the key building to fail then). You can try checking the key is initialised first (privKey.isInitialized())?
    package oracle.forum;
    import javacard.framework.APDU;
    import javacard.framework.Applet;
    import javacard.framework.ISO7816;
    import javacard.framework.ISOException;
    import javacard.security.KeyBuilder;
    import javacard.security.KeyPair;
    import javacard.security.Signature;
    * @author sfarmer
    public class Dummy extends Applet {
         public final static boolean ECHO = true;
         private Signature sig;
         private KeyPair keys;
         public Dummy() {
              sig = Signature.getInstance(Signature.ALG_RSA_SHA_PKCS1, false);
              keys = new KeyPair(KeyPair.ALG_RSA_CRT, KeyBuilder.LENGTH_RSA_2048);
              keys.genKeyPair();
         public static void install(byte[] bArray, short bOffset, byte bLength) {
              // GP-compliant JavaCard applet registration
              new oracle.forum.Dummy().register(bArray, (short) (bOffset + 1),
                        bArray[bOffset]);
         public void process(APDU apdu) {
              // Good practice: Return 9000 on SELECT
              if (selectingApplet()) {
                   return;
              short lc = apdu.setIncomingAndReceive();
              byte[] buf = apdu.getBuffer();
              switch (buf[ISO7816.OFFSET_INS]) {
              case (byte) 0x00:
                   sig.init(keys.getPrivate(), Signature.MODE_SIGN);
                   short len = sig.sign(buf, ISO7816.OFFSET_CDATA, lc, buf, (short) 0);
                   apdu.setOutgoingAndSend((short) 0, len);
                   break;
              default:
                   // good practice: If you don't know the INStruction, say so:
                   ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED);
    }Cheers,
    Shane

  • Signature.Verify()

    Can someone explain this please?
    thnaks
    verify
    public abstract boolean verify(byte[] inBuff,-->Is this a Message Digest?
    short inOffset,
    short inLength,
    byte[] sigBuff,
    short sigOffset,
    short sigLength)
    throws CryptoExceptionVerifies the signature of Parameters:
    inBuff - the input buffer of data to be verified
    inOffset - the offset into the input buffer at which to begin signature generation
    inLength - the byte length to sign
    sigBuff - the input buffer containing signature data
    sigOffset - the offset into sigBuff where signature data begins.
    sigLength - the byte length of the signature data
    Returns:
    true if signature verifies false otherwise.
    If the above answers YES, how does the method refer to the private key to sign it ?

    say u use SHA1_RSA algorithm:
    Signature SHA_RSA;
    RSAPublicKey pk;
    byte[] Exponent = {......};
    byte[] Modulus = {......};
    pk.setExponent(Exponent, offset, length);
    pk.setModulus(Modulus, offset, length);
    SHA_RSA = Signature.getInstance(Signature.ALG_RSA_SHA_PKCS1, false);
    SHA_RSA.init(pk, Signature.MODE_VERIFY);
    boolean pass = SHA_RSA.verify(OriginalData, offset, length, SignatureData, offset, length);
    If the decryption of SignatureData using public key(pk) is equal the OriginalData, then pass = true. Else pass = false.

  • Some questions about javacard 2.1.1 and smartcardio

    Hello i have some question about java card 2.1.1 and the smartcardio package.
    1.) I want to sign a message with the Signature.ALG_RSA_SHA_PKCS1 algorithm. I use the following code in the applet to sign the message:
    final static byte P1_CREATION_MODE = (byte) 0x01;
    final static byte INS_SIGN_MODE = (byte) 0x60;
    final static byte SmartCard_CLA = (byte) 0xB0;
    private void signMessage(APDU apdu) {
            byte[] buffer = apdu.getBuffer();
            byte byteRead = (byte) (apdu.setIncomingAndReceive());
            signature.init(privateKey, Signature.MODE_SIGN);
            short length = signature.sign(buffer, ISO7816.OFFSET_CDATA, byteRead, buffer, (short) 0);
            apdu.setOutgoingLength((short) length);
            apdu.sendBytesLong(buffer, (short) ISO7816.OFFSET_CDATA, (short) length);
            apdu.setOutgoing();
        }On the host side I use the following code to connect to the card and to send the sign apdu:
    if (TerminalFactory.getDefault().terminals().list().size() == 0) {
                LOGGER.log(Level.SEVERE, "No reader present");
                throw new NoSuchCardReader();
            /* Select the first terminal*/
            CardTerminal terminal = TerminalFactory.getDefault().terminals().list().get(0);
            /* Is a card present? */
            if (!terminal.isCardPresent()) {
                LOGGER.log(Level.SEVERE, "No Card present!");
                throw new NoSuchCard();
            /* Set the card protocol */
         Card card = terminal.connect("*");
            ATR atr = card.getATR();
            LOGGER.fine(getHexString(atr.getBytes()));
            LOGGER.fine(getHexString(atr.getHistoricalBytes()));
            CardChannel channel = card.getBasicChannel();
            CommandAPDU cmd = new CommandAPDU((byte) 0xb0, (byte) 0x60, (byte) 0x01, (byte) 0x00, new String("datadatdatadata").getBytes(), (byte) 0x40);
         ResponseAPDU response = channel.transmit(cmd);
            card.disconnect(false);But this does not work and i got the following error
    javax.smartcardio.CardException: sun.security.smartcardio.PCSCException: Unknown error 0x8010002f
            at sun.security.smartcardio.ChannelImpl.doTransmit(ChannelImpl.java:202)
            at sun.security.smartcardio.ChannelImpl.transmit(ChannelImpl.java:73)
            at de.upb.client.smartmeter.SmartMeter.initSmartCardApplet(SmartMeter.java:114)
            at de.upb.client.smartmeter.SmartMeterApplikation.main(SmartMeterApplikation.java:39)
    Caused by: sun.security.smartcardio.PCSCException: Unknown error 0x8010002f
            at sun.security.smartcardio.PCSC.SCardTransmit(Native Method)
            at sun.security.smartcardio.ChannelImpl.doTransmit(ChannelImpl.java:171)
            ... 3 more2.) 3Des encryption
    I want to use the 3Des algorithm to encrypt my data. I use
    keyDES = (DESKey) KeyBuilder.buildKey(KeyBuilder.TYPE_DES,
                        KeyBuilder.LENGTH_DES3_2KEY, false);
    cipherDES = Cipher.getInstance(Cipher.ALG_DES_CBC_ISO9797_M2, false);But i do not know what is the aquivalent on the host side??
    3.) Another problem is that i am not able to send the modulus of a public key from the host applikation to the smard card
    new CommandAPDU((byte) 0xb0, (byte) 0x20, (byte) 0x01, (byte) 0x00, modulus.toByteArray()); // create the apdu
    // the method in the applet
    private void setServerKeyMod(APDU apdu) {
            byte[] buffer = apdu.getBuffer();
            try {
                byte byteRead = (byte) (apdu.setIncomingAndReceive());
                short off = ISO7816.OFFSET_CDATA;
                // strip of any integer padding
                if (buffer[off] == 0) {
                    off++;
                    byteRead--;
                publicKeyServer.setModulus(buffer, off, byteRead);
            } catch (APDUException ex) {
                ISOException.throwIt((short) (SW_APDU_EXCEPTION + ex.getReason()));
        }The error code is 6700
    4.) My last problem ist, that i am not able to use a value bigger than 0x7F as the ne field in the apducommand, because i get the following error
    CommandAPDU((byte) 0xb0, (byte) 0x60, (byte) 0x01, (byte) 0x00, data, (byte) 0xff);
    java.lang.IllegalArgumentException: ne must not be negative
            at javax.smartcardio.CommandAPDU.<init>(CommandAPDU.java:371)
            at javax.smartcardio.CommandAPDU.<init>(CommandAPDU.java:252)I thought that it this should be possible in order to use all the bytes of the response apdu.
    If you need more code to help please let me know.
    Cheers
    Edited by: 858145 on 06.07.2011 08:23

    2) What is PKCS? what is the difference between
    PKCS#11 and PKCS#15??PKCS is the abbreviation of "Public-Key Cryptography Standards"
    PKCS #11: Cryptographic Token Interface Standard
    See http://www.rsasecurity.com/rsalabs/node.asp?id=2133
    PKCS #15: Cryptographic Token Information Format Standard
    http://www.rsasecurity.com/rsalabs/node.asp?id=2141
    If you want to use yor smartcard as secure token it doesn't have to be a JavaCard.
    BTW: I don't remember a way to access PKCS#15 tokens on a JavaCard from within an oncard JavaCard program. If you want to use keys in your oncard program, you have to transfer it onto the card or generate it oncard and export the public key by your own oncard/offcard code.
    Jan

  • "Signing  with JCOP30 "

    Hello everyone,
    I work on JCOP30 smart card and I would like to create a signature with this card ,JCOP 30 can supports RSA algorithm,I use Eclipse tool for programming an Applet.
    I can create signature successfully but when I repeat the creation of signature for more than 20 times(after 21 and somtimes 23 times) I get an error and the status word that it returns is "6F00", ,this error is happened when the Signature wants to get an Instance ,I mean in this line :
    "Signature.getInstance(Signature.ALG_RSA_SHA_PKCS1,false); "
    I do not know what is my mistake ,why it can not create signature ?I should say the private key is defined with this type " RSAPrivateCrtKey" and Jcop30 can support Crt.
    I ran below code with host application(Off-card applet) and with Eclipse simulator, both of them get error when they repeat below code more than 20 times .if anyone knows the reason of this error or had any problem like this please inform me.I would appreciate for any help .
    this is my code :
    //====================================================
         byte[] SignData = new byte[128];      
         Signature sig = null;
         apdu.setIncomingAndReceive();
    byte[] Buffer = apdu.getBuffer();      
         byte[] DataS = new byte[Buffer[(ISO7816.OFFSET_LC )]];
         Util.arrayCopy(Buffer, (short) (ISO7816.OFFSET_LC + 1), DataS,
                        (short) 0, Buffer[ISO7816.OFFSET_LC]);      
              sig = Signature.getInstance(Signature.ALG_RSA_SHA_PKCS1,false);           
              sig.init(privateKey,Signature.MODE_SIGN);           
              sig.sign(DataS,(short)0,(short)DataS.length ,SignData,(short)0);
    //=========================================================
    yours sincerely,
    Orchid

    For analysis it is better to show the whole Applet and the test script/'off-card program' so we can answer questions like:
    - Signature instance in RAM or EEPROM?
    - Approx. free space in EEPROM?
    - Test run in a loop?
    - Any resets between the runs?
    - ATR/ATS settings?
    - Keylength?

  • Help: can't use class: Cipher, Signaure, MessageDigest

    Hi all,
    When I use these Class: Signature or SignatureMessageRecovery, MessageDigest, Cipher in my applet and when I send CreateApplet adpu to the applet, I get some error (SW1SW2=0x6444) and the CREF throw the Exception: SYSTEMEXCEPT_NO_TRANSIENT_SPACE.
    If I change the Signature algorithm to ALG_RSA_SHA_ISO9796_MR and
    cast the Signature Object to SignatureMessageRecovery, I get the same error.
    If I change the Signature algorithm to ALG_DES_MAC8_ISO9797_M2, the applet return success(SW1SW2=9000).
    somebody help me!~
    Thanks!
    code:
    private Signature signature;
    private MessageDigest digest;
    private Cipher cipher;
    private void initSecurityData(){
    digest = MessageDigest.getInstance(MessageDigest.ALG_SHA, false);
    signature = Signature.getInstance(Signature.ALG_RSA_SHA_PKCS1, false);
    cipher = Cipher.getInstance(Cipher.ALG_DES_CBC_ISO9797_M2, false);
    protected CreditCard(byte[] bArray, short bOffset, byte bLength){
    initSecurityData();
    byte aidLen = bArray[bOffset];
    if (aidLen == (byte)0){
    register();
    } else {
    register(bArray, (short)(bOffset+1), aidLen);
    }

    The file is saved as the class name.
    Here's what happens:
    C:\jdk1.2.2\bin>javac HelloWorld.java
    C:\jdk1.2.2\bin>java HelloWorld
    Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorld
    Here's the code that I'm trying to get to run:
    The HelloWorld application program
    public class HelloWorld
         public static void main(String argv[])
              System.out.println("Hello World!");
    }

  • Javacard capacity

    Hi,
    We're looking to use a javacard for cryptographic operations.
    ALG_RSA_PKCS1 for small pieces of data
    ALG_DES_CBC_ISO9797_M2 for larger pieces of data
    ALG_RSA_SHA_PKCS1 to sign large pieces of data
    The card will need generate once and store an internal RSA Key pair (2048), store a single public RSA key (2048) and generate symmetric keys on demand.
    Is it feasible to perform these operations within a java card such as this:
    NXP J2A080 Java Card 80KB
    Global Platform P2.1.1
    JC 2.2.2
    EEPROM 80K
    T=1
    Security Chanel Protocal : 02
    3 Keys (ENC/DEK/MAC) 40h...4fh
    Thanks
    Cheers,
    Phil

    Yes it is. We do (have done) much more than that with the same chip.
    Shane

  • Digital signature headache..

    hi.. i've search this forum.. read through some of the problems and I still can't find the ultimate solution in successfully generating a digital signature on-card. I'm using cyberflex e-gate 32K..
    I've tried using this method here:
    http://forum.java.sun.com/thread.jsp?forum=23&thread=529936&tstart=105&trange=15
    ... but fails because when I tried the ENCRYPT back the DECRYPTED (read the thread above to know what I mean) text sent by the card, I received an error saying that the input is too large for the rsa cipher. the input is too large problem is something like this thread:
    http://forum.java.sun.com/thread.jsp?forum=9&thread=527085&tstart=60&trange=15
    in my card applet, I'm using ALG_RSA_SHA_PKCS1 to sign the data on-card. I went to the cyberflex forum and found something useful:
    http://www.flexforum.com/forums/cyberflexgeneral/293.html
    before using ALG_SHA_PKCS1, I need to manually hash the data using SHA before feeding it to the card for signing..
    this is my card applet's code:
    rsaPrivateCrtKey = (RSAPrivateCrtKey)keyPair.getPrivate();
    rsaPublicKey = (RSAPublicKey)keyPair.getPublic(); // this key is to be exported to the off-card application
    signature = Signature.getInstance(Signature.ALG_RSA_SHA_PKCS1, false);
    // the signing method
    private void signDocs(APDU apdu) {
      byte apduBuffer[] = apdu.getBuffer();           
      short byteRead = (short) (apdu.setIncomingAndReceive());
      // create signature
      signature.init(rsaPrivateCrtKey, Signature.MODE_SIGN);
      signature.sign(apduBuffer, (short)ISO7816.OFFSET_CDATA, byteRead, apduBuffer, (short)0);
      apdu.setOutgoing();
      apdu.setOutgoingLength((short)20);
      apdu.sendBytesLong(apduBuffer, (short)ISO7816.OFFSET_CDATA, (short)20);        
    }this is my off-card application code
    sending the manually SHA1-digested hash to the card
    int iArray[];
    MessageDigest sha = MessageDigest.getInstance("SHA-1");
    String data = "The data to be hashed";
    byte[] dataByte;
    dataByte = data.getBytes();
    sha.update(dataByte);
    byte[] digest = sha.digest();
    iArray = new int[digest.length];
    for (int i=0; i<digest.length; i++) {
         iArray[i] = digest[i] & 0xff;
    sArray = iopCard.SendCardAPDU(CLA, INS, P1, P2, iArray, 20);verifying the signature
    RSAPublicKeySpec rpks = new RSAPublicKeySpec(pubModulus, pubExponent);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    RSAPublicKey rsaPublicKey = (RSAPublicKey)keyFactory.generatePublic(rpks);
    // input the signature bytes
    FileInputStream sigfis = new FileInputStream("output.txt");
    byte[] sigToVerify = new byte[sigfis.available()];
    sigfis.read(sigToVerify);
    sigfis.close();
    // create a Signature object and initialize it with the public key
    Signature sig = Signature.getInstance("SHA1withRSA");
    sig.initVerify(rsaPublicKey);
    // Update and verify the data
    String data = "The data to be hashed";
    // i manually hash the data using SHA-1
    MessageDigest sha = MessageDigest.getInstance("SHA-1");
    byte[] dataByte;
    dataByte = data.getBytes();
    sha.update(dataByte);
    byte[] digest = sha.digest();
    sig.update(digest);
    boolean verifies = sig.verify(sigToVerify); // always return 'false'.. i don't know whyif any of you guys can help me, I really appreciate it.. thanks a lot..

    thank you very very very very very very very very very very very very very very very very much FarAwayFromHome.. the mystery surrounding the digital signature has finally been solved.. I modified my code according to what you asked me to do and yes, the signature returns 128 bytes when I tried to sign a 20 byte data..
    actually, before sending the data to the card for signing, I have to manually hashed it using SHA-1, and then send the hashed data to the card for signing..
    to verify the signature, I have to compare it with the original (pre-hashed) data and it successfully verifies the signature.. thank you so much.. I really appreciate your help.. for reference, I put my codes below:
    sending data for signing (off-card app)
    MessageDigest sha = MessageDigest.getInstance("SHA-1");
    String data = "The data to be hashe";
    byte[] dataByte = data.getBytes();
    sha.update(dataByte);
    byte[] digest = sha.digest();
    iArray = new int[digest.length];
    for (int i=0; i<digest.length; i++) {
         iArray[i] = digest[i] & 0xff;
    sArray = iopCard.SendCardAPDU(CLA, INS, P1, P2, iArray, 128);            
    // save the signature into a file
    DataOutputStream output = new DataOutputStream(new FileOutputStream("output.txt"));
    output.write(sBytes);
    output.close();
    card applet for signing
    private void signDocs(APDU apdu) {
              byte apduBuffer[] = apdu.getBuffer();              
             short byteRead = (short) (apdu.setIncomingAndReceive());       
         // create signature
             signature.init(rsaPrivateCrtKey, Signature.MODE_SIGN);
             short size = signature.sign(apduBuffer, (short)ISO7816.OFFSET_CDATA, byteRead, apduBuffer, (short)ISO7816.OFFSET_CDATA);
             apdu.setOutgoing();
             apdu.setOutgoingLength(size);
             apdu.sendBytesLong(apduBuffer, (short)ISO7816.OFFSET_CDATA, size);
             return;         
    verifying (off-card application)
    // input the signature bytes
    FileInputStream sigfis = new FileInputStream("output.txt");
    byte[] sigToVerify = new byte[sigfis.available()];
    sigfis.read(sigToVerify);
    sigfis.close();
    Signature sig = Signature.getInstance("SHA1withRSA");
    sig.initVerify(rpbk); // rpbk is the public key
    // Update and verify the data
    String data = "The data to be hashe";
    byte[] dataByte = data.getBytes();
    sig.update(dataByte);
    boolean verifies = sig.verify(sigToVerify);
    System.out.println("signature verifies: " + verifies);

  • Install applet failed when calling (RSAPrivateCrtKey)KeyBuilder.buildKey()

    Hi readers,
    I am newbie to Java card applet development. I have written a applet to calculate RSA signature with the fixed RSA CRT components and data sent by CAD.
    When I run the applet using Emulator, I get 0x64 44:
    CLA: 00, INS: a4, P1: 04, P2: 00, Lc: 09, a0, 00, 00, 00, 62, 03, 01, 08, 01, Le: 00, SW1: 90, SW2: 00
    CLA: 80, INS: b8, P1: 00, P2: 00, Lc: 0b, 09, a0, 00, 00, 04, e0, 00, 01, 00, 01, 00, Le: 00, SW1: 64, SW2: 44
    I debugged applet code and I see that below line is the issue.
    privateCrtKey = (RSAPrivateCrtKey)KeyBuilder.buildKey(KeyBuilder.TYPE_RSA_CRT_PRIVATE, KeyBuilder.LENGTH_RSA_2048, false);
    asymSignature = Signature.getInstance(Signature.ALG_RSA_SHA_PKCS1, false);
    please help me to sort out this issue. thanks.

    From ISO 7816-4, 8.6.1
    SW1-SW2 set to '64XX' with the value of 'XX' from '02' to '80' means that the card aborted the command; a possible completion of the command is conditioned by the recovery of a query of 'XX' bytes, for which the card possibly expects a response. (..)In other words, with SW=0x6444, and assuming the standard conventions are used, the card is probably telling that it wants 0x44 bytes in addition of (or is it rather than) the 0x0B it got, in some variant of the original or some additional command.
    Without the source of the applet, or even knowledge of if it is installed or selected, we can't tell much more, except that there is no discernible relation with the lines of source quoted.
    It could also help to know how the idea of sending the C-APDU 80b800000b 09a0000004e00001000100 00 came in the first place.

  • On-card signature w/ ALG_RSA_CRT in JCOP 41 simulator?

    My dev environment is Eclipse 3.0.2, jdk 1.4.2, with JCOP 3.1 pre-release tools.
    I'm using JCRMI with the JCOP 41 simulator.
    I've gotten the stock Sun PhotoCard demo and client to run.
    Now I want to:
    In the simulator:
    1) Generate an oncard key using ALG_RSA_CRT with 512
    2) Use the priv key to create a signature of a photo using ALG_RSA_SHA_PKCS1
    From the terminal:
    3) Get the public modulus of the public key from the card, public exponents are the same.
    4) Get the signature of the photo from the card
    5) Reconstruct a RSAPublicKey using the modulus from the card with a KeyFactory and a RSAPublicKeySpec.
    6) Create a signature verifier using SHA1withRSA
    7) Verify the signature from the card.
    All the data lengths coming back from the card appear correct. There are no exceptions thrown. The verify simpy returns false.
    Before I start posting code, my naive, non-crypto guy question is about RSA versus RSA_CRT. The JCOP 41 simulator can only create RSA_CRT keypairs. The Sun JCE on the terminal only has RSA, not RSA_CRT. This seems to be a likely culprit. Yet it seems to me (non-crypto guy) that the difference only is for the private key not the public key that I'm exporting. Indeed, if there were such a difference it seems like the API would contain a RSACRTPrivateKeySpec, etc.
    Any JCOP 41 users creating keys oncard with success verifying signatures offcard?
    Thanks in advance,
    - Jeff.

    Thanks Jan. Problem solved.
    You confirmed my idea about RSA vs. RSA_CRT. I suspected there was no public key difference. So at least I knew THAT wasn't the problem. It was actually reading (and re-reading) your related thread with Mzee Dubo on RSA signatures that led me to the problem.
    In that thread you questioned the sizes of the mod/exp pair being returned. I knew that those were correct in my case because I was printing the size and values of both. But I had incorrectly assumed that the SHA-1 signature size was going to be 20 bytes, I guess I read that somewhere. (silly non-crypto guy!)
    Once I printed out the actual size of 64 bytes and returned the ENTIRE signature it worked fine. So what's up with 64 bytes? I could have sworn that I read the size was 20 bytes somewhere. Is there some kind of ASN.1 DER encoding going on that makes the byte[] being returned bigger?
    - Jeff

Maybe you are looking for

  • Error message when running form

    hi everybody, im getting this error message when running a simple form. Positional Parameter after key command line. Can anyone please help. thnk u

  • A/R Invoice Closed but Status not Changed

    Hi All, I have Prepared one A/R Invoice Value of Material, Freight, Taxes. To reverse this Invocie, I have passed on A/R Credit Memo but still invoice is showing status as Open-Printed. I have checked JE for both are showing same value. Can any body

  • Books, linked files or... ?

    Sometimes what looks like simple questions starts something complicated... We are trying to manage multiple documents and want to create dynamic links between them. This is what we are trying to do: - We have multiple short documents (1-20 pages each

  • How to use an existing certificate for the ABAP SSL setup using STRUST

    Hi All the documentation say to Create certificate Request and subsequently import the Certificate response from a CA. In our case, the company has a certificate from a valid CA root and we would like to use this when creating the SSL PSE files, in p

  • HT4236 Have ipad2 & iPad camera connection kit - still doesn't download photos on SD card

    Plugged in SD card from camera to a newly purchased ipad2 via the new iPad camera connection kit and it will not download these photos. Tried the same on a friends ipad2 and it works fine. Do I need to download a new app or just update the photo boot