streda 15. augusta 2012

Java, create Hmac SHA1 like in php


private String sha1hash(String sInput){
String sReturn = "";
String sSecret = "1234";

try {
Mac mac = Mac.getInstance("HmacSHA1");
SecretKeySpec secret = new SecretKeySpec(sSecret.getBytes(),"HmacSHA1");
mac.init(secret);
byte[] digest = mac.doFinal(sInput.getBytes());

StringBuffer sb = new StringBuffer();

for (byte b : digest) {
sb.append(String.format("%02x", b));
}

sReturn = sb.toString();
} catch (Exception e) {
//TODO: handle this exception
}
return sReturn;
}

BASE64decode String in java

sInput is base64 encoded string


private String decodeBase64(String sInput){
String sReturn = "";
        BASE64Decoder decoder = new BASE64Decoder();
        try {
          byte[] decodedBytes = decoder.decodeBuffer(sInput);
          sReturn = new String(decodedBytes);
        } catch (IOException e) {
          e.printStackTrace();
        }
        
        return sReturn;
}