BigInteger toByteArray Question

Hi all,
I want to convert BigInteger into byte array using toByteArray method.
However, some errors occur. The length of byte i get from conversion is not same as the original byte length. some are less than original but some are larger.
I have read a 100 byte from a file each time and then convert the byte array into BigInteger for some modulus operation. Finally, i am able to get back the original BigInteger. when i try to convert these BigInteger into byte array, problem arise. some byte array length is 99, some are 100 and some are 101.
Why these happen?
and how to make the conversion successfully?
Thanks

yes.
// Convert the 100 byte array to BigInteger
// open file
byte[] fileByte = MyUtil.openFile("2.jpg");
// New Add Implementation RSA Block
int fileSize = fileByte.length;
int lastBlockSize = fileSize % blockSize;
int numBlock = fileSize / blockSize;
if (lastBlockSize > 0)
numBlock++;
System.out.println("num Block "+numBlock);
System.out.println("last Block Size " + lastBlockSize);
BigInteger[] fileBI = new BigInteger[numBlock];
int j = 0;
for (int i=0; i<numBlock; i++)
     byte[] RSABlock = null;
     // copy the 100 fileByte into RSABlock
     if (i==numBlock-1)
     RSABlock = new byte[lastBlockSize];
     System.arraycopy(fileByte,j, RSABlock,0,lastBlockSize);
     else
     RSABlock = new byte[blockSize];
     System.arraycopy(fileByte,j, RSABlock,0,blockSize);
     j=j+blockSize;
     fileBI[i] = new BigInteger(1,RSABlock); // absolute BigInteger
     System.out.println("Original " + i + " " + fileBI);
// Convert the BigInteger to byte array
for (int i=0; i<customerDe.length; i++ )
if (customerDe[i].compareTo(BigInteger.ZERO) <0 )
System.out.print("NEGATIVE NUMBER");
     if (customerDe[i].compareTo(fileBI[i]) != 0)
     System.out.println("Not Match " + i);
     System.out.println("diff: "+customerDe[i].subtract(fileBI[i]));
     System.exit(1);
     byte[] decryptSigned = customerDe[i].toByteArray();
     byte[] decryptUnsigned = null;
     // if the decryptSigned doesn't have leading Sign || the length is one
     if (decryptSigned[0] != 0x00 || decryptSigned.length == 1)
     System.out.println("UNSigned BYTE "+i);
     decryptUnsigned = decryptSigned;
     System.out.println(i + " len "+ decryptUnsigned.length);
     else if (decryptSigned[0] == 0x00)
     System.out.println("Signed BYTE "+i);
     decryptUnsigned = new byte[decryptSigned.length-1];
     System.arraycopy(decryptSigned,1,decryptUnsigned,0,decryptUnsigned.length);
     System.out.println(i + " len "+ decryptUnsigned.length);
     if (decryptSigned.length == blockSize-1)
     decryptUnsigned = new byte[decryptSigned.length+1];
     System.arraycopy(decryptSigned,0,decryptUnsigned,1,decryptSigned.length);
     baos.write(decryptUnsigned,0,decryptUnsigned.length);

Similar Messages

  • Getting stuck with BigInteger.toByteArray

    I write code that gets data in printable hex representation, converts it to bytes and writes it down to the file (pictures in RTF are stored in this way, so to be precise, I extract pictures from RTF). And here I see the strange behaviour my string is "89504e47..." but file, converted to hex starts with "0089504e47". Could someone explain why BigInteger.toByteArray have added '0' to the byte array? I reproduced this on this simple code (identical to my app's code)
    BigInteger temp = new BigInteger("89", 16);
    System.out.println("byte: " + temp.toByteArray()[0]);output:
    byte: 0

    The javadoc for toByteArray says:
    "Returns a byte array containing the two's-complement representation of this BigInteger. The byte array will be in big-endian byte-order: the most significant byte is in the zeroth element. The array will contain the minimum number of bytes required to represent this BigInteger, including at least one sign bit"
    The byte that you see as zero is the one that contains the sign bit.
    Kaj

  • Convert Double to a ByteArray

    I need to convert several values to Byte Arrays so that they can be transmitted in a DataGramPacket. One of these values is a Double. What is the best way to do this? The data contained in the double needs not have a scale greater than 4.
    With other values such as Shorts or Longs, I can represent them using a BigInteger and use BigInteger.toByteArray, but am unable to do this with Doubles as I would lose everything after the decimal point.
    Thanks in advance

    Knowing that a double is a 64 bits value, which means it has the same number of bytes than a "long", you can produce a long value that represents your double
    long l = Double.doubleToRawLongBits(d)where d is the double you want to represent as a byte array. And then you can use this new long as an ordinary long number.
    To get your double back, just use
    double Double.longBitsToDouble(long l)

  • Question on RsaPrivateKey

    hi guys,
    I ve generate a a pair of keys rsa and then I ve stored the modulus and the privateExponent of the private key in two differents byte arrays. So.. my question is.
    If I use the value of modulus and privateExponent Can I rebuild the privateKey ?
    java.security.KeyFactory keyFactory =
               java.security.KeyFactory.getInstance("RSA", "IAIK");
    java.security.spec.RSAPrivateKeySpec params =
                      new java.security.spec.RSAPrivateKeySpec (modulus, exp );
    java.security.PrivateKey privKey =
                        keyFactory.generatePrivate(params);Is it sufficient? If I print the privateKey using the method getEncoded() I ve different value first and after the key "rebuild".
    what's wrong?
    thanks
    Edited by: emanuele.g on Jun 13, 2009 8:11 AM

    Must I use the RSA CRT class to rebuild correctly private key? Is There no another way?
    Generate Key's pair.
                    gen = KeyPairGenerator.getInstance("RSA", "IAIK");
                    gen.initialize(keyLength);
                    pair = gen.genKeyPair();
    }Saving Modulus and Exponent.
    byte[] modulus;
    byte[]exponent;
    RSAPrivateKeyImp ( java.security.PrivateKey key, short le ) {
                length = le;
            try{
                java.security.interfaces.RSAPrivateKey k =
                    (java.security.interfaces.RSAPrivateKey) key;
                modulus = k.getModulus().toByteArray();
                exponent = k.getPrivateExponent().toByteArray();
            }catch (Exception e){ System.out.println ("in RSAPrivateKeyImp: " +e.getMessage()); e.printStackTrace();}
    short len = key.getModulus(data, (short)0);
    byte[] key_data = new byte[len];
    Util.arrayCopy(data, (short)0, key_data, (short)0, len);
      BigInteger modulus = new BigInteger(key_data);
    short len = key.getExponent(data, (short)0)
    byte[] key_data = new byte[len];
    Util.arrayCopy(data, (short)0, key_data, (short)0, len);
      BigInteger exp = new BigInteger(key_data);Edited by: emanuele.g on Jun 13, 2009 8:51 AM

  • Trying to send multiple types in a byte array -- questions?

    Hi,
    I have a question which I would really appreciate any help on.
    I am trying to send a byte array, that contains multiple types using a UDP app. and then receive it on the other end.
    So far I have been able to do this using the following code. Please note that I create a new String, Float or Double object to be able to correctly send and receive. Here is the code:
    //this is on the client side...
    String mymessage ="Here is your stuff from your client" ;
    int nbr = 22; Double nbr2 = new Double(1232.11223);
    Float nbr3 = new Float(8098098.809808);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(mymessage);
    oos.writeInt(nbr);
    oos.writeObject(nbr2);
    oos.writeObject(nbr3);
    oos.close();
    byte[] buffer = baos.toByteArray();
    socket.send(packet);
    //this is on the server side...
    byte [] buffer = new byte [5000];
    String mymessage = null; int nbr = 0; Double nbr2 = null;
    Float nbr3 = null;
    mymessage = (String)ois.readObject();
    nbr = ois.readInt();
    nbr2 = (Double) ois.readObject();
    nbr3 = (Float) ois.readObject();
    My main question here is that I have to create a new Float and Double object to be able to send and receive this byte array correctly. However, I would like to be able to have to only create 1object, stuff it with the String, int, Float and Double, send it and then correctly receive it on the other end.
    So I tried creating another class, and then creating an obj of this class and stuffing it with the 4 types:
    public class O_struct{
    //the indiv. objects to be sent...
    public String mymessage; public int nbr; public Double nbr2;
    public Float nbr3;
    //construct...
    public O_struct(String mymessage_c, int nbr_c, double nbr2_c, float nbr3_c){
    my_message = my_message_c;
    nbr = nbr_c;
    nbr2 = new Double(nbr2_c);
    nbr3 = new Float(nbr3_c);
    Then in main, using this new class:
    in main():
    O_struct some_obj_client = new O_struct("Here is your stuff from your client", 22, 1232.1234, 890980980.798);
    oos.writeObject(some_obj_client);
    oos.close();
    send code....according to UDP
    However on the receiving side, I am not sure how to be able to correctly retrieve the 4 types. Before I was explicitely creating those objects for sending, then I was casting them again on the receiving side to retrieve then and it does work.
    But if I create a O_struct object and cast it as I did before with the indiv objects on the receiving end, I can't get the correct retrievals.
    My code, on the server side:
    O_struct some_obj_server = new O_struct(null, null, null. null);
    some_obj_server = (O_struct)ois.readObject();
    My main goal is to be able to send 4 types in a byte array, but the way I have written this code, I have to create a Float and Double obj to be able to send and receive correctly. I would rather not have to directly create these objects, but instead be able to stuff all 4 types into a byte array and then send it and correctly be able to retrieve all the info on the receiver's side.
    I might be making this more complicated than needed, but this was the only way I could figure out how to do this and any help will be greatly appreciated.
    If there an easier way to do I certainly will appreciate that advise as well.
    Thanks.

    public class O_struct implements Serializable {
    // writing
    ObjectOutputStream oos = ...;
    O_struct struct = ...;
    oos.writeObject(struct);
    // reading
    ObjectInputStream ois = ...;
    O_struct struct = (O_struct)ois.readObject();
    I will be sending 1000s of these byte arrays, and I'm sure having to create a new Double or Float on both ends will hinder this.
    I am worried that having to create new objs every time it is sending a byte array will affect my application.
    That's the wrong way to approach this. You're talking about adding complexity to your code and fuglifying it because you think it might improve performance. But you don't know if it will, or by how much, or even if it needs to be improved.
    Personally, I'd guess that the I/O will have a much bigger affect on performance than object creation (which, contrary to popular belief, is generally quite fast now: http://www-128.ibm.com/developerworks/java/library/j-jtp01274.html)
    If you think object creation is going to be a problem, then before you go and cock up your real code to work around it, create some tests that measure how fast it is one way vs. the other. Then only use the cock-up if the normal, easier to write and maintain way is too slow AND the cock-up is significantly faster.

  • [BUG] NUMBER(38) to BigInteger mapping error. JDev 11.1.2.1.0

    When I try to update value in af:table, popup error says "Invalid column type" (in WL logs - "java.sql.SQLException: Invalid column type")
    Though SELECT succeeds, i.e. I can see table's data
    *[EDIT]* This is not bug from 11.1.2.0, attribute type is java.math.BigInteger, not just BigInteger *[EDIT]*
    Steps to reproduce:
    1. table
    CREATE TABLE anm_tmp( i NUMBER(38) PRIMARY KEY );
    BEGIN
       INSERT INTO anm_tmp( i ) VALUES( 1 );
       INSERT INTO anm_tmp( i ) VALUES( 2 );
       COMMIT;  
    END;2. create "Business Component from Tables"
    3. create single page, add af:table, add commit button
    Workaround
    change attribute's type to BigDecimal or Integer (open entity object, go to "Attributes" tab, "Details" tab)
    Questions
    1. Is this really a bug, or I've missed smth ?
    2. Should I choose BigDecimal or Integer (or smth else) ?
    *[EDIT 2]*
    Configuration: <pre>
    CPU: Intel E5300
    OS: Windows 7 (x32)
    JDev:
    build: JDEVADF_11.1.2.1.0_GENERIC_110907.2314.6081
    Java: 1.6.0_24
    Oracle IDE: 11.1.2.1.38.60.81
    </pre>
    Edited by: Alexander Malakhov on Apr 4, 2012 10:16 AM

    Alexander,
    The reason you don't see bug 11672797 is that it was filed by an internal employee and thus not externalized. The bug summary is:
    Looks like JDBC is having trouble with BigInteger for a column of type NUMBER(38).
    JDBC VERSION AND NAME OF JDBC JAR FILE (REQUIRED):
    JDBCDriverVersion: 11.2.0.2.0
    DatabaseProductName: Oracle
    DatabaseProductVersion: Oracle Database 11g Enterprise Edition Release
    11.1.0.7.0 - Production With the Partitioning, OLAP, Data Mining and Real
    Application Testing options
    This bug has been fixed in November 2011 and has been filed against the JDBC driver. The fix is available in version 12.1 (backport appears to be feasible)
    Anyway, If this issue only reproduces in JDeveloper 11g R2 and not for 11.1.1.5 then chances are that indeed the issue might be different. So if it reproduces for you then please go ahead and file a bug. I am spending larger parts of my time trying to reproduce issues reported on OTN. If things don't reproduce for me but you have a reproducible testcase, please file a bug so the issue is fixed once you upgrade to a next release
    Frank

  • Very Large Numbers Question

    I am a student with a question about how Java handles very large numbers. Regarding this from our teacher: "...the program produces values that
    are larger than Java can represent and the obvious way to test their size does not
    work. That means that a test that uses >= rather than < won?t work properly, and you
    will have to devise something else..." I am wondering about the semantics of that statement.
    Does Java "know" the number in order to use it in other types of mathematical expressions, or does Java "see" the value only as gibberish?
    I am waiting on a response from the teacher on whether we are allowed to use BigInteger and the like, BTW. As the given program stands, double is used. Thanks for any help understanding this issue!

    You're gonna love this one...
    package forums;
    class IntegerOverflowTesterator
      public static void main(String[] args) {
        int i = Integer.MAX_VALUE -1;
        while (i>0) {
          System.out.println("DEBUG: i="+i);
          i++;
    }You also need to handle the negative case... and that get's nasty real fast... A positive plus/times a positive may overflow, but so might a negative plus a negative.
    This is decent summary of the underlying problem http://mindprod.com/jgloss/gotchas.html#OVERFLOW.
    The POSIX specification also worth reading regarding floating point arithmetic standards... Start here http://en.wikipedia.org/wiki/POSIX I guess... and I suppose the JLS might be worth a look to http://java.sun.com/docs/books/jls/second_edition/html/typesValues.doc.html

  • I have a question about socket

    I've got a socket question that haven't to work out for two days . If you know something about this question please give me a hand , Thank you .............
    ===================================================
    I want to write a program about PortMapping with Java.
    It means : put one port's data to another port .
    =============================
    Just like :
    There is a Tomcat Web Server listener on the 8080 port, and I want to make a socket that listener on the 9090 port. When the client use the Browse visit my web on 9090 port , this socket will be send this data stream from 9090 port to 8080 port and then the Tomcat Web Server process this data and return the result to client use the 9090 port .
    =============================
    (In order to let this program suit for every model (include c/s and b/s),so I think it must be use the byte[] stream )
    ====================================================
    BinaryPort.java
    package sailing;
    import java.io.*;
    import java.net.*;
    public class BinaryPort implements Runnable
    private ServerSocket listenerSocket;
    private Socket serverSocket;
    private Socket tomcatSocket;
    private Thread myThread;
    private DataInputStream in;
    private DataOutputStream out;
    private ByteArrayOutputStream swapStream;
    public BinaryPort()
    try
    System.out.println("Server is starting ..................");
    this.listenerSocket=new ServerSocket(9090);
    this.tomcatSocket=new Socket("127.0.0.1",8080);
    this.swapStream=new ByteArrayOutputStream();
    this.myThread=new Thread(this);
    this.myThread.start();
    catch(Exception e)
    System.out.println(e);
    public void run()
    while(true)
    try
    this.serverSocket=this.listenerSocket.accept();
    this.in=new DataInputStream(this.serverSocket.getInputStream());
    byte[] buf=new byte[100];
    int rc=0;
    while((rc=in.read(buf,0,buf.length))>0)
    this.swapStream.write(buf,0,rc);
    this.swapStream.flush();
    byte[] resBuf=swapStream.toByteArray();
    this.out=new DataOutputStream(this.tomcatSocket.getOutputStream());
    this.out.write(resBuf,0,resBuf.length);
    this.out.flush();
    //Get The Tomcat Web Server reBack Information
    this.in=new DataInputStream(this.tomcatSocket.getInputStream());
    byte[] buf2=new byte[100];
    int rc2=0;
    this.swapStream=null;
    while((rc2=in.read(buf2,0,buf2.length))>0)
    this.swapStream.write(buf2,0,rc2);
    this.swapStream.flush();
    rc2=0;
    byte[] resBuf2=swapStream.toByteArray();
    this.out=new DataOutputStream(this.serverSocket.getOutputStream());
    this.out.write(resBuf2,0,resBuf2.length);
    this.out.flush();
    this.myThread.sleep(1000);
    this.out.close();
    this.in.close();
    catch(Exception e)
    System.out.println(e);
    public static void main(String args[])
    new BinaryPort();
    ====================================================
    I found that it stop on the first "while" , and I don't know what is the reason .............

    Well , I've got it ~~~~~~~~~
    if the read method hasn't the another data , this method will be stoped . so ..............
    ===============================
    package sailing;
    import java.io.*;
    import java.net.*;
    public class ModifyBinaryPort
         private ServerSocket listenerSocket;
         private Socket serverSocket;
         public ModifyBinaryPort()
              try
                   System.out.println("Server is starting ..................");
                   this.listenerSocket=new ServerSocket(9633);
                   while(true)
                        try
                             this.serverSocket=this.listenerSocket.accept();
                             new MyThread(serverSocket).start();                    
                        catch(Exception e)
                             System.out.println(e);
              catch(Exception e)
                   System.out.println(e);
         public static void main(String args[])
              new ModifyBinaryPort();
         class MyThread extends Thread
              private Socket threadSocket;
              private Socket tomcatSocket;
              private Thread myThread;
              private DataInputStream in;
              private DataOutputStream out;
              public MyThread(Socket socket)
                   try
                        threadSocket=socket;
                        this.tomcatSocket=new Socket("127.0.0.1",9090);
                   catch(Exception e)
                        System.out.println(e);
              public void run()
                   try
                        //Read Thread
                        new ReadClientWriteTomcatThread(threadSocket,tomcatSocket).start();                    
                   catch(Exception e)
                             System.out.println(e);
         class ReadClientWriteTomcatThread extends Thread
              private DataInputStream read;
              private DataOutputStream write;
              private ByteArrayOutputStream swapStream;
              private Socket threadSocket;
              private Socket tomcatSocket;
              public ReadClientWriteTomcatThread(Socket threadSocketT,Socket tomcatSocketT)
                   try
                        threadSocket=threadSocketT;
                        tomcatSocket=tomcatSocketT;
                        read=new DataInputStream(threadSocket.getInputStream());
                        write=new DataOutputStream(tomcatSocket.getOutputStream());
                        this.swapStream=new ByteArrayOutputStream();
                   catch(Exception e)
                        System.out.println(e);
              public void run()
                   try
                        byte[] buf=new byte[100];
                        int rc=0;
                        while((rc=read.read(buf,0,buf.length))>0)
                             this.swapStream.write(buf,0,rc);
                             this.swapStream.flush();
                             if(rc<buf.length)
                                  break;
                             //System.out.println(rc);
                        byte[] resBuf=swapStream.toByteArray();
                        this.write.write(resBuf,0,resBuf.length);
                        this.write.flush();
                        //Reading the result from tomcat
                        new ReadTomcatWriteClientThread(threadSocket,tomcatSocket).start();
                   catch(Exception e)
                        System.out.println(e);
         class ReadTomcatWriteClientThread extends Thread
              private DataInputStream read;
              private DataOutputStream write;
              private ByteArrayOutputStream swapStream;
              public ReadTomcatWriteClientThread(Socket threadSocket,Socket tomcatSocket)
                   try
                        read=new DataInputStream(tomcatSocket.getInputStream());
                        write=new DataOutputStream(threadSocket.getOutputStream());
                        this.swapStream=new ByteArrayOutputStream();
                   catch(Exception e)
                        System.out.println(e);
              public void run()
                   try
                        byte[] buf2=new byte[100];
                        int rc2=0;
                        while((rc2=read.read(buf2,0,buf2.length))>0)
                             this.swapStream.write(buf2,0,rc2);
                             this.swapStream.flush();
                             if(rc2<buf2.length)
                                  break;
                        byte[] resBuf2=swapStream.toByteArray();
                        this.write=new DataOutputStream(write);
                        this.write.write(resBuf2,0,resBuf2.length);
                        this.write.flush();          
                        this.write.close();
                        this.read.close();
                   catch(Exception e)
                        System.out.println(e);
    }==================
    but it still has some little bug , I think I will work out soon .........
    Thanks for your help ejp .............

  • 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

  • Options to insert a BigInteger in a file

    Good days,
    As the title says, this more than a doubt is a search of alternatives.
    I have a program that performs calculations whose result is a number of several dozens of thousands of digits saved in a variable of type BigInteger. At the moment of returning the result, I use a file to save it.
    The problem appears at the moment of handling the number to be able to insert it in the file, because it takes a lot of time. In the last execution that I have done, it took 8 minutes to compute, 19 minutes to transform the BigInteger to a String and barely a second to insert it into the file.
    The question is whether anyone knows any more efficient way to perform this step, perhaps with an alternative class to BufferedWriter that I have used to insert in the file and in which we need a char or String as a parameter.
    Is important that the file could be read directly by a human.
    Regards and thanks.

    I don't know how NIO API can help me.
    The only quick way I've found to insert the BigInteger in a file is using an ObjectOutputStream, but this creates a file unreadable to me and when I use the method toString() to insert as a String having it readable, it takes too time.
    Before opening this item, I've been looking all the types of buffers and OutpuStreams that I found on the API, several of them mentioned in the NIO API, and I've tested to see if some served me. At the end I haven't found any which allow me to avoid the method toString().
    Edited by: JaimeLG on Sep 8, 2008 12:35 PM

  • Question about character encoding

    Hey everyone,
    I've been trying to read about character encodings and how Java IO uses them, however, there is something I still don't understand:
    I am trying to read an HTML file encoded in UTF-8 and which contain some Arabic characters.
    I used this code to save it on a file:
    URL u = new URL("http://www.fatafeat.com");    // some Arabic website
    URLConnection connection = u.openConnection();
    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
    OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream("datat.txt"));
    int c;
    while ((c = reader.read())!=-1)
    writer.write(c);However, the output on the file is always "??????"
    I used another version of the code
    URL u = new URL("http://www.fatafeat.com");     //some Arabic website
    URLConnection connection = u.openConnection();
    InputStream reader = connection.getInputStream();
    FileOutputStream writer = new FileOutputStream("datat.txt");
    int c;
    while ((c = reader.read()) != -1)
    writer.write(c);And I get on the file something like this " ÇáæÍíÏÉ áÝä "
    I tried to open the file from a browser using a UTF-8 encoding, but still the same display. What am I missing here? Thanks

    Upon further investigation, my initial hunch appears to be correct. The page in question is not correctly encoded UTF-8, so the Java decoder fails. By default, the java decoder fails silently and replaces malformed input with the character "\uFFFD". If you want more control over the decoding process, you need to read the data as bytes and use the CharsetDecoder class to convert to characters. Here is small example to illustrate:
    import java.io.ByteArrayOutputStream;
    import java.io.CharArrayWriter;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.URL;
    import java.nio.ByteBuffer;
    import java.nio.CharBuffer;
    import java.nio.charset.Charset;
    import java.nio.charset.CharsetDecoder;
    import java.nio.charset.CoderResult;
    import java.nio.charset.CodingErrorAction;
    public class FatafeatToy3
        private static final Charset UTF8 = Charset.forName("UTF-8");
        private static final Charset DEFAULT_DECODER_CHARSET = UTF8;
        private final CharsetDecoder decoder;
        public FatafeatToy3(final Charset cs)
            this.decoder = cs.newDecoder();
            this.decoder.onMalformedInput(CodingErrorAction.REPORT);
            this.decoder.onUnmappableCharacter(CodingErrorAction.REPORT);
        public FatafeatToy3()
            this(DEFAULT_DECODER_CHARSET);
        public ByteBuffer pageSlurp (URL url) throws IOException
            ByteArrayOutputStream pageBytes = new ByteArrayOutputStream ();
            InputStream is = url.openStream();
            int ch;
            while ((ch = is.read()) != -1)
                pageBytes.write(ch);
            is.close();
            return ByteBuffer.wrap(pageBytes.toByteArray());
        public CoderResult decodeSome(ByteBuffer in, CharBuffer out)
            decoder.reset();
            CoderResult result = decoder.decode(in, out, true);
            if (result.isMalformed())
                System.err.printf("Malformed input detected at pos 0x%x%n", in.position());
            else if (result.isUnmappable())
                System.err.printf("Unmappable input detected at pos 0x%x%n", in.position());
            else if (result.isUnderflow())
                result = decoder.flush(out);
            return result;
        public static void main(String[] args) throws Exception
            FatafeatToy3 ft = new FatafeatToy3();
            ByteBuffer in = ft.pageSlurp(new URL("http://www.fatafeat.com"));
            System.out.printf("Page slurped contains %d bytes%n", in.capacity());
            CharBuffer out = CharBuffer.allocate(1); // one character at a time
            CharArrayWriter pageChars = new CharArrayWriter();
            CoderResult result = CoderResult.UNDERFLOW;
            while ( (! result.isError()) && in.remaining() > 0)
                result = ft.decodeSome(in, out);
                if (result.equals(CoderResult.OVERFLOW))
                    out.flip();
                    pageChars.append(out);
                    out.clear();
    }

  • Socket read delay question

    I'm having a delay problem only on Solaris 10 using the Tomcat connector from IIS to Solaris.
    I've posted this issue on a couple of Java forums with no luck. Hopefully, this forum will have the correct audience.
    I have:
    - IIS 6, Windows 2003 Server on dual PIII with jk 1.2.15 installed and working.
    - Solaris 10 on Sun E420R with Quad Processors with jBoss / Tomcat version 4.0.3SP1 installed and working.
    There is a significant delay in page loading that occurs randomly (every 10-20 clicks) which lasts for 10-18 or so seconds.
    I've traced it to a read() method in the ChannelSocket.java file on the AJP (i.e. Tomcat / Solaris 10) side.
    The delay always occurs while the receive() method is reading the header portion of the message.
    The length of the header that the read is trying to read is 4 bytes. The call to BufferedInputStream()
    will block until it gets these 4 bytes of the header (10-18 seconds). I've modified the Java code
    and put a call in to available() before and after the read. The before returns 0 and the after returns 1138 or so.
    I've tried every imaginable combination of configs on the IIS side to get around the problem ... and then
    some kernel TCP/IP configs on the Solaris side ... too many to list here.
    The problem seems to be isolated to Solaris ... because Linux, XP, Windows 2003 server all work without this problem.
    My question is this ... is there any thing that I can configure to have this read return faster?
    Changes to the Solaris kernel ... some config parameter ... ?? Anyone experience this before?
    I'll gladly list the things I've tried to get some idea of how to solve this.
    I think ultimately this is my problem: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4479751
    Thanks in advance!

    Hi!
    Try this...
    Socket connection = new Socket(server,port);
    // use a Buffered*Stream as often as possible, because
    // of the IP Packet Lengths...It Increases the
    // network performance (but you DON'T need it)
    // you'll send bytes or messages to the server in
    // the OutputStream and receive answers from the
    // server in the InputStream
    int packetOutputBufferSize = connection.getSendBufferSize();
    int packetInputBufferSize = connection.getReceiveBufferSize();
    BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream(),packetOutputBufferSize);
    BufferedInputStream bis = new BufferedInputStream(connection.getInputStream(),packetInputBufferSize);
    // sending data through the socket
    // create your packet in a byte array
    byte[] output = new byte[<packet-lenght>];
    output[0]=<packet ID>
    output[1]=....
    bos.write(output,0,output.length);
    // receiving data from the socket
    byte[] input = new byte[<max-packet-length>];
    int read=0;
    int length=0;
    while ((read=bis.read(input,length,(input.length-length)) > 0) {
    length+=read;
    if (length>=input.length) break;
    // now your server output is in the bytearray 'input'
    If it isn't possible to set a max packet size, use a bytearray as buffer and write it content into a ByteArrayOutputStream, thats something like a resizable write-only byte array. (you'll get the full content of it by calling the method ByteArrayOutputStream.toByteArray())
    Maybe you want to check the packet content during receiving the bytes from the socket: Then you should use some read() method from the InputStream, but thats not very powerful.

  • Using BigInteger as primarykey

    Hi,
    When I use BigInteger as primary key and use the sequence with it I get this exception
    java.lang.ClassCastException: java.lang.Long
         at com.sleepycat.persist.impl.SimpleFormat$FBigInt.writeObject(SimpleFormat.java:767)
         at com.sleepycat.persist.impl.PersistKeyAssigner.assignPrimaryKey(PersistKeyAssigner.java:50)
         at com.sleepycat.persist.PrimaryIndex.assignKey(PrimaryIndex.java:487)
         at com.sleepycat.persist.PrimaryIndex.put(PrimaryIndex.java:338)
         at com.sleepycat.persist.PrimaryIndex.put(PrimaryIndex.java:314)
    SimpleFormat is trying to cast the Long value to bigInteger and thats how the class cast
    exception is raised.
    My question is can we use bigInteger with the DPL sequence like
    @PrimaryKey(sequence="seq_my_entity")
    private BigInteger my_pk;
    What my understanding is that BigInteger is included in the simple datatypes of the DPL, and it should support the autogeneration of BigInt keys.
    One more thing what will happen when primary key having the type long runs out of value, like there are millions of record.
    Thanks,
    Shoaib

    Hello Shoaib,
    Primary key sequences are not currently allowed with BigInteger keys. See the javadoc for PrimaryKey.sequence:
    http://www.oracle.com/technology/documentation/berkeley-db/je/java/com/sleepycat/persist/model/PrimaryKey.html#sequence()
    To use a sequence, the type of the key field must be a primitive integer type (byte, short, int or long) or the primitive wrapper class for one of these types.
    We do not currently support BigInteger sequences because (as you point out) JE sequences are limited to long values, and BigInteger can contain much larger values. This limitation is in the JE base API Sequence class, not the DPL.
    However, you should have received a more informative error message, not a ClassCastException. We'll fix that in a future release.
    If you need values larger than a long, and you would like to assign them from a sequence, you can use a BigInteger key and implement a sequence yourself. I suggesting implementing a singleton sequence class that increments the sequence in memory, in a synchronized method, for example:
    private BigInteger lastValue;
    synchronized BigInteger getNext() {
        lastValue = lastValue.add(BigInteger.ONE);
        return lastValue;
    }When opening the store, initialize the sequence from the largest existing key; for example:
    PrimaryIndex<BigInteger,MyData> priIndex = ...
    EntityCursor<BigInteger> keys = priIndex.keys();
    try {
       lastValue = keys.last();
    } finally {
       keys.close();
    if (lastValue == null) {
        lastValue = BigInteger.ONE;
    }Does this help?
    Mark

  • Another question?? being able to send byte arrays containing multiple types

    Hi,
    I have a question which I would really appreciate any help on.
    I am trying to send a byte array, that contains multiple types using a UDP app. and then receive it on the other end.
    So far I have been able to do this using the following code. Please note that I create a new String, Float or Double object to be able to correctly send and receive. Here is the code:
    //this is on the client side...
    String mymessage ="Here is your stuff from your client" ;
    int nbr = 22; Double nbr2 = new Double(1232.11223);
    Float nbr3 = new Float(8098098.809808);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(mymessage);
    oos.writeInt(nbr);
    oos.writeObject(nbr2);
    oos.writeObject(nbr3);
    oos.close();
    byte[] buffer = baos.toByteArray();
    socket.send(packet);
    //this is on the server side...
    byte [] buffer = new byte [5000];
    String mymessage = null; int nbr = 0; Double nbr2 = null;
    Float nbr3 = null;
    mymessage = (String)ois.readObject();
    nbr = ois.readInt();
    nbr2 = (Double) ois.readObject();
    nbr3 = (Float) ois.readObject();
    My main question here is that I have to create a new Float and Double object to be able to send and receive this byte array correctly. However, I would like to be able to have to only create 1object, stuff it with the String, int, Float and Double, send it and then correctly receive it on the other end.
    So I tried creating another class, and then creating an obj of this class and stuffing it with the 4 types:
    public class O_struct{ 
    //the indiv. objects to be sent...
    public String mymessage; public int nbr; public Double nbr2;
    public Float nbr3;
    //construct...
    public O_struct(String mymessage_c, int nbr_c, double nbr2_c, float nbr3_c){
    my_message = my_message_c;
    nbr = nbr_c;
    nbr2 = new Double(nbr2_c);
    nbr3 = new Float(nbr3_c);
    Then in main, using this new class:
    in main():
    O_struct some_obj_client = new O_struct("Here is your stuff from your client", 22, 1232.1234, 890980980.798);
    oos.writeObject(some_obj_client);
    oos.close();
    send code....according to UDP
    However on the receiving side, I am not sure how to be able to correctly retrieve the 4 types. Before I was explicitely creating those objects for sending, then I was casting them again on the receiving side to retrieve then and it does work.
    But if I create a O_struct object and cast it as I did before with the indiv objects on the receiving end, I can't get the correct retrievals.
    My code, on the server side:
    O_struct some_obj_server = new O_struct(null, null, null. null);
    some_obj_server = (O_struct)ois.readObject();
    My main goal is to be able to send 4 types in a byte array, but the way I have written this code, I have to create a Float and Double obj to be able to send and receive correctly. I would rather not have to directly create these objects, but rather just create one object and be able to send and receive the information on both ends
    I might be making this more complicated than needed, but this was the only way I could figure out how to do this and any help will be greatly appreciated.
    If there an easier way to do I certainly will appreciate that advise as well.
    Thanks.

    which forum should I be posting this on?Serialization.
    To get you started...
    public class O_struct implements Serializable {                                                                                                                                                                                                                                                                                   

  • Adding arrays - confusing question

    I am in the process of writing a java program where I have to add arrays. The question asks:
    This program asks you to assume that your computer has the very limited capability of being able to read and write only single-digit integers and to add together two integers consisting of one decimal digit each. Write a program that can read in two integers of up to 40 digits each, add these digits together, and display the result. Test your program using pairs of numbers of varying lengths. You must use arrays in this problem.
    I think I understand up to there is says"Write a program that can read in two integers of up to 40 digits each" from there I am lost.
    Can anyone help explain what is needed?
    This is what i have so far:
    import java.util.*;
    public class add
        public static void main(String[] args)
          Scanner in = new Scanner(System.in);
          int x = in.nextInt();
          int y = in.nextInt();
            int[] a = {x};
            int[] b = {y};
            int[] ab = new int[a.length + b.length];
            System.arraycopy(a, 0, ab, 0, a.length);
            System.arraycopy(b, 0, ab, a.length, b.length);
            System.out.println(Arrays.toString(ab));
    }

    Yeh, sorry about that didn't have the time to go ahead and drag some of the code over when I first found this forum, first thing I tried a quick compile and run just to see what problems I'd get and I got this runtime error of: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 7
         at java.lang.String.charAt(String.java:687)
         at Joseph_Ryan_P2.main(Joseph_Ryan_P2.java:36)
    I threw in some print statements to see how far it gets before the error occurs and it seems to be right before the for loop(see code below)
    In this program I'm reading in from a text file that will read two numbers from the same line that are seperated by a space and eventually add them, is the best way to do that by using a tokenizer or some sort of space delimiter? Or is there an easier way? If the tokenizer is best how would i go about that I haven't learned too much about them besides the fact that they exist so far.
    Thanks for any help you or suggestions you guys can give.
    //Joseph_Ryan_P2.java
    //Big Integer Program
    //Description:
    //     Design and implement a BigInteger class that can add and subtract integers with up to 25 digits. Your
    //     class should also include methods for input and output of the numbers.
    // Must Use Arrays
    import java.io.*;               //neccessary imported libraries
    import java.util.*;
    public class Joseph_Ryan_P2          
         public static void main(String[] args)          //the programs main method
              try
                   Scanner scan = new Scanner(new File("BigInts")); //Scanner to read in from plaintext file
              String numline = scan.next();
              int x=0;
              int [] big1 = new int [numline.length()];
              System.out.println(numline);
                   int [] big2 = new int [numline2.length()];
                   String numline2= scan.nextLine();
                   System.out.println(numline2);
              for(int i = numline.length() - 1; i >= 0; i++)
              char current = numline.charAt(i);
              int d = (int) current - (int) '0';
                   big1[i] = d;
              }//end for loop
              }//end try
              catch(FileNotFoundException exception)
    System.out.println("The file could not be found.");
    catch(IOException exception)
    System.out.println(exception);
    } //end catch statements
         }//end main
    }//end class

Maybe you are looking for

  • How to download anyconnect vpn client 64 bit win 7

    Good day all, please i wanted to download anyconnect vpn client 64 bit win 7 from software.cisco.com and i was not able to do that after login in. please can someone help me on how or the steps i can take to get the download. secondly can i be able t

  • What is a PHP server and how do I make it work??

    I've heard about it, and I'm trying to make form, but apparently you need a PHP server.  What is it and where do I get one and how do I make it work??? Thanks! Happy flashing!

  • Disk Utility hanging on Erase/Partition OR Howto backup a dual boot Mactel?

    I'm trying to use Disk Utility to format an external usb hd as HFS+ for backing up my Macbook. Running 10.4.7 and Disk Util 10.5.6 (latest version afaik) Problem is whenever I try to either Erase format a hard drive using my usb2 external enclosure,

  • How do I permanently delete purchases?

    I delete a purchased song from itunes and send it to recycle bin.  But the next time I sync, itunes automatically transfers it back to my library.  How do I permanently delete purchased items?  This problem seemed to start once I started using icloud

  • Simulation Interface Toolkit - How to toggle a manual switch in simulink from LabVIEW?

    I have a manual switch in my simulink diagram that I want to use to switch between to values from my LabVIEW interface. I have tried to connect a toggle switch at LabVIEW`s VI with different parameters in the simulink model(I can choose betweenhow Po