Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
   *
   * Copyright (c) 2013-2014 sagyf Yang. The Four Group.
   */
  
  package com.github.sog.libs;
  
 
 import java.util.UUID;

.

Author(s):
sagyf yang
Version:
1.0 2014-04-04 10:22
Since:
JDK 1.6
 
 public class Codec {


    

Returns:
an UUID String
 
     public static String UUID() {
         return UUID.randomUUID().toString();
     }

    
Encode a String to base64

Parameters:
value The plain String
Returns:
The base64 encoded String
 
     public static String encodeBASE64(String value) {
         try {
             return new String(Base64.encodeBase64(value.getBytes(.)));
         } catch (UnsupportedEncodingException ex) {
             throw new UnexpectedException(ex);
         }
     }

    
Encode binary data to base64

Parameters:
value The binary data
Returns:
The base64 encoded String
 
     public static String encodeBASE64(byte[] value) {
         return new String(Base64.encodeBase64(value));
     }

    
Decode a base64 value

Parameters:
value The base64 encoded String
Returns:
decoded binary data
 
     public static byte[] decodeBASE64(String value) {
         try {
             return Base64.decodeBase64(value.getBytes(.));
         } catch (UnsupportedEncodingException ex) {
             throw new UnexpectedException(ex);
         }
     }

    
Build an hexadecimal MD5 hash for a String

Parameters:
value The String to hash
Returns:
An hexadecimal Hash
 
     public static String hexMD5(String value) {
         try {
             MessageDigest messageDigest = MessageDigest.getInstance("MD5");
             messageDigest.reset();
             messageDigest.update(value.getBytes("utf-8"));
             byte[] digest = messageDigest.digest();
             return byteToHexString(digest);
         } catch (Exception ex) {
             throw new UnexpectedException(ex);
         }
     }

    
Build an hexadecimal SHA1 hash for a String

Parameters:
value The String to hash
Returns:
An hexadecimal Hash
 
    public static String hexSHA1(String value) {
        try {
            MessageDigest md;
            md = MessageDigest.getInstance("SHA-1");
            md.update(value.getBytes("utf-8"));
            byte[] digest = md.digest();
            return byteToHexString(digest);
        } catch (Exception ex) {
            throw new UnexpectedException(ex);
        }
    }

    
Write a byte array as hexadecimal String.
    public static String byteToHexString(byte[] bytes) {
        return String.valueOf(Hex.encodeHex(bytes));
    }

    
Transform an hexadecimal String to a byte array.
    public static byte[] hexStringToByte(String hexString) {
        try {
            return Hex.decodeHex(hexString.toCharArray());
        } catch (DecoderException e) {
            throw new UnexpectedException(e);
        }
    }
New to GrepCode? Check out our FAQ X