简体   繁体   中英

Why encrypted and base64 encoded text appears different on Windows and Linux

I have a legacy system that uses hibernate interceptor to encrypt (and encode) and decrypt (and decode) some fields on some database tables. It makes use of the OnSave, OnLoad and OnFlushDirty methods. This code turns out to be buggy as data read from this system, when transferred to another application still has some of the records encrypted and encoded (some encrypted multiple times). The challenge for me here is that I could perform the decryption and decoding (as many times as necessary) when the receiving application is on a Windows machine. I get a BadPaddingException when I try to repeat the same thing when the receiving application is a linux VM.

Any help/suggestions will be greatly appreciated

here is a snippet of the hibernate interceptor

public boolean onLoad(Object entity, Serializable arg1, Object[] state, String[]  propertyNames, Type[] arg4) throws CallbackException {
if (key != null){
 try {
  if (entity instanceof BasicData) {
   for (int i = 0; i < state.length; i++) {

     if (state[i] instanceof String){
       String cipherText = (String)state[i];
       byte[] cipherTextBytes = Base64Coder.decode(cipherText);
       byte[] plainTextBytes = dCipher.doFinal(cipherTextBytes);
       state[i] = new String(plainTextBytes, "UTF8");
    }
 }
 return true;
}
} catch (Exception e) {
  e.printStackTrace();
}}return false;}

I'd have to guess here but if you mean this Base64Coder the problem might be the following:

It is unclear how the base64 string has been created, ie which encoding had been used. If you use UTF-8 to get the bytes of a string and create a base64 from those bytes you'll get a different result than if you'd use ISO Latin-1, for example.

Afterwards you create a string from those bytes using UTF-8, but if the base64 string had not been created using UTF-8, you'll get wrong results.

Just a quote from the linked source (if this is the correct one):

 public static String encodeString (String s) {
   return new String(encode(s.getBytes())); }

Here, s.getBytes() will use the system's/jvm's default encoding, so you should really ensure it is UTF-8!

If you control both sides, encode and decode, better way to use DatatypeConverter:

String          buffer          = DatatypeConverter.printBase64Binary( symKey );
byte[]          supposedSymKey  = DatatypeConverter.parseBase64Binary( buffer );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM