프로그래밍(~2017)/자바

[자바] HMAC-SHA1 + Base64

단세포소년 2011. 8. 9. 06:57
반응형

private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";

 

 

String data = "fadafadsfasdfad";

String key = "asdfasd"

 

String sol = null;
          
try {
     byte[] rel = Base64_HMACSHA1(data, key);
      sol = new String(rel);
     } catch (SignatureException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
     }
et4.setText(sol);

 

 

 

public static byte[] Base64_HMACSHA1(String data, String key)
   throws java.security.SignatureException
  {
   byte[] rawHmac = null;
   
   try {
  
    // get an hmac_sha1 key from the raw key bytes
    SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);
   
    // get an hmac_sha1 Mac instance and initialize with the signing key
    Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
    mac.init(signingKey);
   
    // compute the hmac on input data bytes
    rawHmac = mac.doFinal(data.getBytes());
    
   } catch (Exception e) {
      throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
   }
   
   //return rawHmac;
     
    
   byte [] buf = null;
       
      try {
        
       Class Base64 = Class.forName("org.apache.commons.codec.binary.Base64");
          Class[] parameterTypes = new Class[] { byte[].class };  
          Method encodeBase64 = Base64.getMethod("encodeBase64", parameterTypes);
          buf = (byte[])encodeBase64.invoke(Base64, rawHmac);
           
      } catch (Exception e) {
          e.printStackTrace();
      }            
       
      return buf;
  
  }


반응형