Venkat Pathy
Venkat Pathy

Reputation: 151

Validating Base64 Encoded String

For the following code when i try to base64 encode a string.

import org.apache.commons.codec.binary.Base64;

public class Codec {
  public static void main(String[] args) {
      String clrTxt = "Hello world";
      String encodedTxt;

      encodedText = new String(Base64.encodeBase64(clearText.getBytes()));
      System.out.println("Encoded: " + encodedText);
      System.out.println("Decoded:" 
          + new String(Base64.decodeBase64(encodedText.getBytes())));
      //    
      // output :
      //   Encoded: **SGVsbG8gd29ybGQ=**
      //   Decoded:Hello world      
  }
}

In the encoded String when i try to insert some extraa characters, say --> "SGVsb*G8ASDFASDFASDFASDFASDF1234234*gd29ybGQ=" -> i get a clear text with some diacritical characters in it. Is there a method to validate and overcome this. Please reply. Thanks in advance.

Upvotes: 3

Views: 5968

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

You have very limited ability to validate a base-64 string all by itself: as long as the encoded string has the correct length (i.e. the length, including the trailing equal signs, is divisible by four) and the string consists of only proper base64 characters, it is deemed a valid string.

If you need to tamper-proof your message, you need to prepare an additional piece of data describing the original text, and pass it to the destination along with your base64 encoded data. In the simplest case, it could be a checksum of the text, but that scheme is easy to beat. A better approach is to prepare a digest of the original text using a cryptographic hash function, and pass that digest along with the base64 encoded text to the destination.

Keep in mind that passing a digest will not prevent man-in-the-middle attacks, because the attacker can send his own digest along with a tampered message.

Upvotes: 3

Related Questions