Ron - 6 months ago 26

Java Question

I use AES to encrypt a 17-digit number (for example, 12345678901234567), then I Base64-encode the

`byte[]`

Is there a way to my goal by any

algorithm( AES, DES, 3DES ..)? And how?

My DES encrypt algorithm,

`public static byte[] encrypt(byte[] datasource, String password) {`

try{

SecureRandom random = new SecureRandom();

DESKeySpec desKey = new DESKeySpec(password.getBytes());

SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");

SecretKey securekey = keyFactory.generateSecret(desKey);

Cipher cipher = Cipher.getInstance("DES");

cipher.init(Cipher.ENCRYPT_MODE, securekey, random);

return cipher.doFinal(datasource);

}catch(Throwable e){

e.printStackTrace();

}

return null;

}

private static void longToByteArray(long l, byte[] b) {

b[7] = (byte) (l);

l >>>= 8;

b[6] = (byte) (l);

l >>>= 8;

b[5] = (byte) (l);

l >>>= 8;

b[4] = (byte) (l);

l >>>= 8;

b[3] = (byte) (l);

l >>>= 8;

b[2] = (byte) (l);

l >>>= 8;

b[1] = (byte) (l);

l >>>= 8;

b[0] = (byte) (l);

}

long aliveTime = Long.parseLong("13664547854160806");

byte[] longAsBytes = new byte[8];

longToByteArray(aliveTime, longAsBytes);

byte[] result = DES.encrypt(longAsBytes, password);

String en = REncrypt.base64Encode(result);

Answer

An encryption algorithm will not compress data. Indeed, if anything, the encrypted data will be harder to compress than the original. The "scrambling" that the encryption algorithm performs will make any redundancy in the encrypted data harder (probably impossible) to extract.

A better approach would be to compress the 17 digit number *before* you encrypt it. In this case, converting the decimal characters into a binary number will probably give better compression than a text compression algorithm. A 17 digit number will fit into 8 bytes; i.e. a Java `long`

.

So here's what I would do:

- Convert the decimal digits to a
`long`

; i.e. parse it using`Long.parseLong`

or similar. - Split the
`long`

into 8 bytes, and put them into a`byte[]`

. - Encrypt the
`byte[]`

. The result should be 8 bytes. - Base64 encode the bytes.

If you do it this way, your encrypted, base64 encoded number should be less than 15 characters.

Note: I'm assuming that you really mean encrypt; i.e. that you need to be able to decrypt and recover the original number.

**UPDATE**

This probably won't work with many / most decent encryption algorithms because they typically have a minimum block size that is too large. See https://en.wikipedia.org/wiki/Block_size_(cryptography). If you read the article, you will get some insight into why that is so.