The following code can be used to convert a byte array (containing the bytes of a long) into a long.
public static long byteArrayToLong(byte[] bytes) {
long l = 0;
for (int i=0; i<8; i++) {
l <<= 8;
l ^= (long) bytes[i] & 0xff;
}
return l;
}
This is the reverse of “How to convert a long to a byte array“.
written by objects
\\ tags: array, byte array, conversion, long, representation
Once you have generated a SecretKey you can use it’s getEncoded() method to generate a byte array that can be used to recreate the key.
// Use the following to initially create a random key
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
kgen.init(256);
SecretKey key = keyGen.generateKey();
// Then use the following to get the
byte[] encoded = key.getEncoded();
// byte array could now be saved for later use to recreate key
To then recreate your key using the byte array, you can use the following:
SecretKey key = new SecretKeySpec(encoded, "AES");
written by objects
\\ tags: AES, byte array, encoded, JCE, KeyGenerator, SecretKey
The following code can be used to extract the 8 bytes from a long value and return them as a byte array
public static byte[] longToByteArray(long data) {
return new byte[] {
(byte)((data >> 56) & 0xff),
(byte)((data >> 48) & 0xff),
(byte)((data >> 40) & 0xff),
(byte)((data >> 32) & 0xff),
(byte)((data >> 24) & 0xff),
(byte)((data >> 16) & 0xff),
(byte)((data >> 8 ) & 0xff),
(byte)((data >> 0) & 0xff),
};
}
written by objects
\\ tags: array, byte array, conversion, long, representation