JavaBlog.fr / Java.lu Cryptology,DEVELOPMENT,Java Java – Crypto : Encoding with base64, base64url, rfc-4648

Java – Crypto : Encoding with base64, base64url, rfc-4648

Hello,
Through several articles, I would like present the cryptographic mechanisms, types of keys, certificate, types of algorithms …etc:

 


Encoding base64, base64url, rfc-4648
 

  1. Presentation
    Base64 is an encoding using 65 characters mainly used in the messages transfer on Internet. The goal is not to keep information secret, but rather to ensure that it’s able to be properly consumed.
    An alphabet of 65 characters is used to allow the representation of 6 bits by a character. The 65th character (sign “=”) is used only as a final complement in the coding process of a message.
     
    Disadvantages
    This coding increases the size of the data: the size of the data is increased by at least one third. The “white” characters (space, tab, line break) increase the size even more.

    With this encoding, even the readable characters in the original data are encrypted illegibly. If the majority of the characters of an initial text are already readable, it is possible to envisage coding only the problematic characters.
     
    Advantages
    Advantages The advantage of base64 encoding is not to be found in the representation of textual data, but especially in the representation of binary data.

    When one wants to represent binary data (an image, an executable) in a textual document, such as an email, the hexadecimal transcription in ASCII of the bytes would multiply the size by two, base64 encoding makes it possible to limit this increase.

     
    Base64url
    RFC 4648 provides an alternative for encoding compatible with file names and URIs. In fact, the 62 (+) and 63 (/) characters can cause problems with some file systems and URIs. The solution chosen consists of replacing these characters with a minus (-) and an underlined (_) respectively. The complement character remains “=”, but can be ignored.

     

  2. Solution and Tools
    Summary, Base64 encoding allows to have an output string without special characters: conversion of bytes into characters.
    * Use of sun.misc.BASE64Decoder and sun.misc.BASE64Encoder
    * Use of org.apache.commons.codec.binary.Base64 (commons-codec-X.Y.jar) : With the usage of Base64 from Apache Commons, who can be configured to URL safe
    * Other solution since JAVA 8 : use of java.util.Base64 : http://farenda.com/java/java-base64-url/

     

  3. Example Base64
    	/**
    	 * Use of sun.misc.BASE64Decoder and sun.misc.BASE64Encoder
    	 */
    	private static String sun_misc_base64Encode(byte[] bytes) {
    		return new sun.misc.BASE64Encoder().encode(bytes);
    	}
    	private static byte[] sun_misc_base64Decode(String property) throws IOException {
    		return new sun.misc.BASE64Decoder().decodeBuffer(property);
    	}
    	
    	/**
    	 * Use of org.apache.commons.codec.binary.Base64 (commons-codec-X.Y.jar)
    	 */
    	private static String apache_commons_codec_base64Encode(byte[] bytes) {
    		return new String(new org.apache.commons.codec.binary.Base64().encode(bytes));
    	}
    	private static byte[] apache_commons_codec_base64Decode(String property) throws IOException {
    		return new org.apache.commons.codec.binary.Base64().decode(property.getBytes());
    	}
    

     
    …here the main method:

    public static void main(String[] args) {
    		try {
    			String str = "123456ds fds àçèé#&çer çer "+System.getProperty("line.separator")+" ^rrr 7897ezrz";
    			//
    			{
    				System.out.println("-------- Use of sun.misc.BASE64Decoder and sun.misc.BASE64Encoder ");
    				System.out.println("Original=" + str);
    				String strEnc = sun_misc_base64Encode(str.getBytes());
    				System.out.println("Encoded=" + strEnc);
    				String strDec = new String(sun_misc_base64Decode(strEnc));
    				System.out.println("Decoded=" + strDec);
    				System.out.println("Decoded is equal to Original=" + (strDec.equals(str)));
    			}
    			{
    				System.out.println("-------- Use of org.apache.commons.codec.binary.Base64 (commons-codec-X.Y.jar) ");
    				System.out.println("Original=" + str);
    				String strEnc = apache_commons_codec_base64Encode(str.getBytes());
    				System.out.println("Encoded=" + strEnc);
    				String strDec = new String(apache_commons_codec_base64Decode(strEnc));
    				System.out.println("Decoded=" + strDec);
    				System.out.println("Decoded is equal to Original=" + (strDec.equals(str)));
    			}
    			{
    				System.out.println("-------- Use of sun.misc.BASE64Decoder and sun.misc.BASE64Encoder and org.apache.commons.codec.binary.Base64 (commons-codec-X.Y.jar) ");
    				System.out.println("Original=" + str);
    				String strEnc = sun_misc_base64Encode(str.getBytes());
    				System.out.println("Encoded=" + strEnc);
    				String strDec = new String(apache_commons_codec_base64Decode(strEnc));
    				System.out.println("Decoded=" + strDec);
    				System.out.println("Decoded is equal to Original=" + (strDec.equals(str)));
    			}
    
    			
    		} catch (Exception ex) {
    			ex.printStackTrace();
    		}
    	}
    

     
    …here the outputs:

    -------- Use of sun.misc.BASE64Decoder and sun.misc.BASE64Encoder
    Original=123456ds fds àçèé#&çer çer
    ^rrr 7897ezrz
    Encoded=MTIzNDU2ZHMgZmRzIODn6OkjJudlciDnZXIgDQogXnJyciA3ODk3ZXpyeg==
    Decoded=123456ds fds àçèé#&çer çer
    ^rrr 7897ezrz
    Decoded is equal to Original=true
    -------- Use of org.apache.commons.codec.binary.Base64 (commons-codec-X.Y.jar)
    Original=123456ds fds àçèé#&çer çer
    ^rrr 7897ezrz
    Encoded=MTIzNDU2ZHMgZmRzIODn6OkjJudlciDnZXIgDQogXnJyciA3ODk3ZXpyeg==
    Decoded=123456ds fds àçèé#&çer çer
    ^rrr 7897ezrz
    Decoded is equal to Original=true
    -------- Use of sun.misc.BASE64Decoder and sun.misc.BASE64Encoder and org.apache.commons.codec.binary.Base64 (commons-codec-X.Y.jar)
    Original=123456ds fds àçèé#&çer çer
    ^rrr 7897ezrz
    Encoded=MTIzNDU2ZHMgZmRzIODn6OkjJudlciDnZXIgDQogXnJyciA3ODk3ZXpyeg==
    Decoded=123456ds fds àçèé#&çer çer
    ^rrr 7897ezrz
    Decoded is equal to Original=true

     

  4. Example Base64Url
    	public static String encode(final byte[] content) {
    		final String base64string = new BASE64Encoder().encode(content);
    		
    		System.out.println("Before base64url : " + base64string);
    		
    		String base64urlString = base64string.replace('+', '-'); // 62nd char of encoding
    		base64urlString = base64urlString.replace('/', '_');	 // 63rd char of encoding
    		
    		while (base64urlString.endsWith("=")) { // Remove any trailing '='s
    			base64urlString = base64urlString.substring(0, base64urlString.length() -1);
    		}
    
    		System.out.println("After base64url : " + base64urlString);
    
    		return base64urlString;
    	}
    	
    	public static byte[] decode(final String content) throws IOException {
    		String base64string = content.replace('-', '+'); // 62nd char of encoding
    		base64string = base64string.replace('_', '/');	 // 63rd char of encoding
    		
    		if (base64string.length() % 4 == 2) {
    			base64string += "==";
    		} else if (base64string.length() % 4 == 3) {
    			base64string += "=";
    		}
    
    		System.out.println("Before base64 decode : " + base64string);
    
    		return new BASE64Decoder().decodeBuffer(base64string);
    	}
    

     
    …here the main method:

        private static final String VALUE = "Hello world !";
    
    	public static void main(String[] args) {
            try {
    			final String encodedValue = Base64Url.encode(VALUE.getBytes());
    			System.out.println("Original=" + VALUE);
    			System.out.println("Encoded=" + encodedValue);
    			final byte[] decodedValue = Base64Url.decode(encodedValue);
    			System.out.println("Decoded=" + new String(decodedValue));
    			System.out.println("Decoded is equal to Original=" + (VALUE.equals(new String(decodedValue))));
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
        }
    

     
    …here the outputs:

    Before base64url : SGVsbG8gd29ybGQgIQ==
    After base64url : SGVsbG8gd29ybGQgIQ
    Original=Hello world !
    Encoded=SGVsbG8gd29ybGQgIQ
    Before base64 decode : SGVsbG8gd29ybGQgIQ==
    Decoded=Hello world !
    Decoded is equal to Original=true

     

Sources : base64.zip

That’s all!!!

Huseyin OZVEREN

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.

Related Post