Using java to encrypt integers

后端 未结 7 1500
野性不改
野性不改 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:02

    You can turn ints into a byte[] using a DataOutputStream, like this:

    ByteArrayOutputStream baos = new ByteArrayOutputStream ();
    DataOutputStream dos = new DataOutputStream (baos);
    dos.writeInt (i);
    byte[] data = baos.toByteArray();
    // do encryption
    

    Then to decrypt it later:

    byte[] decrypted = decrypt (data);
    ByteArrayInputStream bais = new ByteArrayInputStream (data);
    DataInputStream dis = new DataInputStream (bais);
    int j = dis.readInt();
    

提交回复
热议问题