Created
May 12, 2014 09:08
-
-
Save iambigd/0d7e9f7dc0e5672bf989 to your computer and use it in GitHub Desktop.
Create signature with HMAC
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.UnsupportedEncodingException; | |
import java.security.GeneralSecurityException; | |
import java.security.SecureRandom; | |
import java.util.Random; | |
import javax.crypto.Mac; | |
import javax.crypto.spec.SecretKeySpec; | |
import org.apache.commons.codec.binary.Base64; | |
/** | |
* Signature Helper | |
* @author kenwctsai | |
* @date 2014/4/18 | |
**/ | |
public class SignatureHelper { | |
static String HAMC_SHA256 = "HmacSHA256"; | |
static int SALT_LEN = 32; | |
public static String getNextSaltedHash(){ | |
final Random r = new SecureRandom(); | |
byte[] saltByte = new byte[SALT_LEN]; | |
r.nextBytes(saltByte); | |
String saltedKey = new String(saltByte); | |
return saltedKey; | |
} | |
public static String generateHmacSHA256Signature(String salt,String key) | |
throws GeneralSecurityException{ | |
String signature = null; | |
try { | |
SecretKeySpec secret_key = new SecretKeySpec( | |
key.getBytes(), | |
SignatureHelper.HAMC_SHA256); | |
Mac sha256_HMAC = Mac.getInstance(SignatureHelper.HAMC_SHA256); | |
sha256_HMAC.init(secret_key); | |
// signature = Base64.encodeBase64String( | |
// sha256_HMAC.doFinal(salt.getBytes("UTF-8"))); | |
//modified by ken 2014/5/12 | |
signature = Base64.encodeBase64URLSafeString( | |
sha256_HMAC.doFinal(salt.getBytes("UTF-8"))); | |
return signature; | |
} catch (UnsupportedEncodingException e) { | |
throw new GeneralSecurityException(e); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
base64用到的字元: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=
由於base64會包含 + / = ,當把他當url querystring時,要記得做相關的url encode/url decode,
要避免掉的話可以改用這個方法Base64.encodeBase64URLSafeString