Using java to encrypt integers

后端 未结 7 1591
野性不改
野性不改 2021-02-03 14:14

I\'m trying to encrypt some integers in java using java.security and javax.crypto.

The problem seems to be that the Cipher class only encrypts byte arrays. I can\'t d

7条回答
  •  轮回少年
    2021-02-03 15:11

    Just use NIO. It's designed for this specific purpose. ByteBuffer and IntBuffer will do what you need quickly, efficiently, and elegantly. It'll handle big/little endian conversion, "direct" buffers for high performance IO, and you can even mix data types into the byte buffer.

    Convert integers into bytes:

    ByteBuffer bbuffer = ByteBuffer.allocate(4*theIntArray.length);
    IntBuffer ibuffer = bbuffer.asIntBuffer(); //wrapper--doesn't allocate more memory
    ibuffer.put(theIntArray);                  //add your int's here; can use 
                                               //array if you want
    byte[] rawBytes = bbuffer.array();         //returns array backed by bbuffer--
                                               //i.e. *doesn't* allocate more memory
    

    Convert bytes into integers:

    ByteBuffer bbuffer = ByteBuffer.wrap(rawBytes);
    IntBuffer ibuffer = bbuffer.asIntBuffer();
    while(ibuffer.hasRemaining())
       System.out.println(ibuffer.get());      //also has bulk operators
    

提交回复
热议问题