
goja.core.libs.Codec Maven / Gradle / Ivy
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2013-2014 sagyf Yang. The Four Group.
*/
package goja.core.libs;
import goja.core.StringPool;
import goja.core.exceptions.UnexpectedException;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.util.UUID;
/**
*
* .
*
*
* @author sagyf yang
* @version 1.0 2014-04-04 10:22
* @since JDK 1.6
*/
public class Codec {
/**
* @return an UUID String
*/
public static String UUID() {
return UUID.randomUUID().toString();
}
/**
* Encode a String to base64
*
* @param value The plain String
* @return The base64 encoded String
*/
public static String encodeBASE64(String value) {
try {
return new String(Base64.encodeBase64(value.getBytes(StringPool.UTF_8)));
} catch (UnsupportedEncodingException ex) {
throw new UnexpectedException(ex);
}
}
/**
* Encode binary data to base64
*
* @param value The binary data
* @return The base64 encoded String
*/
public static String encodeBASE64(byte[] value) {
return new String(Base64.encodeBase64(value));
}
/**
* Decode a base64 value
*
* @param value The base64 encoded String
* @return decoded binary data
*/
public static byte[] decodeBASE64(String value) {
try {
return Base64.decodeBase64(value.getBytes(StringPool.UTF_8));
} catch (UnsupportedEncodingException ex) {
throw new UnexpectedException(ex);
}
}
/**
* Build an hexadecimal MD5 hash for a String
*
* @param value The String to hash
* @return 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
*
* @param value The String to hash
* @return 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);
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy