Ron Ron - 2 months ago 5x
Java Question

could a 17-digit encrypts into a 15-digit by AES or other algorithms

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

. The length of the final result string is 24. I want to barcode it, the 24 characters are too long. One string which consists of 15 characters would be good, and about 15-digits (for example 123456789012345 ) would be better.

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) {
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){
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);


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:

  1. Convert the decimal digits to a long; i.e. parse it using Long.parseLong or similar.
  2. Split the long into 8 bytes, and put them into a byte[].
  3. Encrypt the byte[]. The result should be 8 bytes.
  4. 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.


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