下面列出了javax.crypto.Mac#init ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* HmacMD2消息摘要
*
* @param data
* 待做消息摘要处理的数据
* @param key
* 密钥
*
* @return byte[] 消息摘要
*
* @throws Exception
*/
public static byte[] encodeHmacMD2(byte[] data, byte[] key) throws NoSuchAlgorithmException, InvalidKeyException {
// 加入BouncyCastleProvider支持
Security.addProvider(new BouncyCastleProvider());
// 还原密钥
SecretKey secretKey = new SecretKeySpec(key, "HmacMD2");
// 实例化Mac
Mac mac = Mac.getInstance(secretKey.getAlgorithm());
// 初始化Mac
mac.init(secretKey);
// 执行消息摘要
return mac.doFinal(data);
}
/**
* Constant-time equality check.
*/
private boolean safeEquals(ByteBuffer signature, byte[] calculatedSig) {
try {
signature.rewind();
Mac hmac = Mac.getInstance(hmacComparisonKey.getAlgorithm());
hmac.init(hmacComparisonKey);
hmac.update(signature);
byte[] signatureHash = hmac.doFinal();
hmac.reset();
hmac.update(calculatedSig);
byte[] calculatedHash = hmac.doFinal();
return MessageDigest.isEqual(signatureHash, calculatedHash);
} catch (GeneralSecurityException ex) {
// We've hardcoded these algorithms, so the error should not be possible.
throw new RuntimeException("Unexpected exception", ex);
}
}
/**
* Implementation of HMAC encryption
*/
public static String encrypt(HMAC.Method method, byte[] key, byte[] message) throws Exception{
SecretKeySpec keySpec = new SecretKeySpec(key, method.getMethod());
Mac cipher = Mac.getInstance(method.getMethod());
cipher.init(keySpec);
byte[] cipherText = cipher.doFinal(message);
StringBuffer hash = new StringBuffer();
for (int i = 0; i < cipherText.length; i++) {
String hex = Integer.toHexString(0xFF & cipherText[i]);
if (hex.length() == 1) {
hash.append('0');
}
hash.append(hex);
}
return hash.toString();
}
private byte[] computeSignature(String baseString)
throws GeneralSecurityException, UnsupportedEncodingException {
SecretKey key = null;
synchronized (this) {
if (this.key == null) {
String keyString = OAuth.percentEncode(getConsumerSecret())
+ '&' + OAuth.percentEncode(getTokenSecret());
byte[] keyBytes = keyString.getBytes(ENCODING);
this.key = new SecretKeySpec(keyBytes, MAC_NAME);
}
key = this.key;
}
Mac mac = Mac.getInstance(MAC_NAME);
mac.init(key);
byte[] text = baseString.getBytes(ENCODING);
return mac.doFinal(text);
}
/**
* Get the truncated HMAC
*/
protected byte[] getHmac(byte[] key, byte[] msg)
throws GeneralSecurityException {
SecretKey keyKi = new SecretKeySpec(key, "HMAC");
Mac m = Mac.getInstance("HmacSHA1");
m.init(keyKi);
// generate hash
byte[] hash = m.doFinal(msg);
// truncate hash
byte[] output = new byte[hashSize];
System.arraycopy(hash, 0, output, 0, hashSize);
return output;
}
@Override
public void doTest(String alg) throws NoSuchAlgorithmException,
InvalidKeyException, NoSuchProviderException {
SecretKey key = Utils.getSecretKeySpec();
// instantiate Mac object and init it with a SecretKey
Mac mac = Mac.getInstance(alg, "SunJCE");
mac.init(key);
try {
ByteBuffer buf = null;
mac.update(buf);
mac.doFinal();
throw new RuntimeException(
"Expected IllegalArgumentException not thrown");
} catch (IllegalArgumentException e) {
System.out.println("Expected IllegalArgumentException thrown: "
+ e);
}
}
public static String Hmac(String secret, String data) {
try {
SecretKeySpec signingKey = new SecretKeySpec(secret.getBytes(), HMAC_SHA1_ALGORITHM);
Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
mac.init(signingKey);
byte[] rawHmac = mac.doFinal(data.getBytes());
String result = Base64.encodeToString(rawHmac, Base64.NO_WRAP);
return result;
} catch (GeneralSecurityException e) {
throw new IllegalArgumentException();
}
}
private static byte[] hmacSha256(byte[] key, String value) {
try {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(key, "HmacSHA256"));
return mac.doFinal(value.getBytes(StandardCharsets.UTF_8));
}
catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw new UnsupportedOperationException(e.getMessage(), e);
}
}
/**
* hmac HmacSHA256
*
* @param message 信息
* @param secret 秘钥
* @return 加密结果
*/
public static String hmacSha256(String message, String secret) {
Exception exception = null;
try {
Mac mac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
mac.init(secretKeySpec);
return HexUtil.hexEncode(mac.doFinal(message.getBytes()), false);
} catch (NoSuchAlgorithmException ignored) {
} catch (InvalidKeyException e) {
e.printStackTrace();
exception = e;
}
throw new ExchangeException("hmacSha256 error.", exception);
}
@Override
public void doTest(String alg) throws NoSuchAlgorithmException,
InvalidKeyException, NoSuchProviderException {
SecretKey key = Utils.getSecretKeySpec();
// instantiate Mac object and init it with a SecretKey
Mac mac = Mac.getInstance(alg, "SunJCE");
mac.init(key);
// prepare buffer
byte[] data = new byte[BUFFER_SIZE];
for (int i = 0; i < BUFFER_SIZE; i++) {
data[i] = (byte) (i % 256);
}
ByteBuffer buf = ByteBuffer.wrap(data);
int limitBefore = buf.limit();
mac.update(buf);
mac.doFinal();
int limitAfter = buf.limit();
int positonAfter = buf.position();
if (limitAfter != limitBefore) {
System.out.println("limit after = " + limitAfter);
System.out.println("limit before = " + limitBefore);
throw new RuntimeException("Test failed: "
+ "limit of buffer has been chenged.");
}
if (positonAfter != limitAfter) {
System.out.println("position after = " + positonAfter);
System.out.println("limit after = " + limitAfter);
throw new RuntimeException("Test failed: "
+ "position of buffer isn't equal to its limit");
}
}
public static String hmacSha1(String value, String key) {
try {
byte[] keyBytes = key.getBytes("UTF-8");
SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(signingKey);
byte[] rawHmac = mac.doFinal(value.getBytes());
byte[] hexBytes = new Hex().encode(rawHmac);
return new String(hexBytes, "UTF-8");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private byte[] calculateMac(char[] passwd, byte[] data)
throws IOException
{
byte[] mData = null;
String algName = macAlgorithm.substring(7);
try {
// Generate a random salt.
byte[] salt = getSalt();
// generate MAC (MAC key is generated within JCE)
Mac m = Mac.getInstance(macAlgorithm);
PBEParameterSpec params =
new PBEParameterSpec(salt, macIterationCount);
SecretKey key = getPBEKey(passwd);
m.init(key, params);
m.update(data);
byte[] macResult = m.doFinal();
// encode as MacData
MacData macData = new MacData(algName, macResult, salt,
macIterationCount);
DerOutputStream bytes = new DerOutputStream();
bytes.write(macData.getEncoded());
mData = bytes.toByteArray();
} catch (Exception e) {
throw new IOException("calculateMac failed: " + e, e);
}
return mData;
}
private Mac createHmac(final byte[] keyBytes, String hmacName) throws Exception
{
SecretKeySpec key = new SecretKeySpec(keyBytes, hmacName);
Mac mac = Mac.getInstance(hmacName);
mac.init(key);
return mac;
}
private String returnTradingAPICommandResults(String commandValue, List<NameValuePair> additionalPostParams) {
try {
List<NameValuePair> postParams = new ArrayList<>();
postParams.add(new BasicNameValuePair("command", commandValue));
postParams.add(new BasicNameValuePair("nonce", String.valueOf(System.currentTimeMillis())));
if (additionalPostParams != null && additionalPostParams.size() > 0) {
postParams.addAll(additionalPostParams);
}
StringBuilder sb = new StringBuilder();
for (NameValuePair postParam : postParams) {
if (sb.length() > 0) {
sb.append("&");
}
sb.append(postParam.getName()).append("=").append(postParam.getValue());
}
String body = sb.toString();
Mac mac = Mac.getInstance("HmacSHA512");
mac.init(new SecretKeySpec(apiSecret.getBytes(), "HmacSHA512"));
String signature = new String(Hex.encodeHex(mac.doFinal(body.getBytes())));
List<NameValuePair> httpHeaders = new ArrayList<>();
httpHeaders.add(new BasicNameValuePair("Key", apiKey));
httpHeaders.add(new BasicNameValuePair("Sign", signature));
return client.postHttp(TRADING_URL, postParams, httpHeaders);
} catch (IOException | NoSuchAlgorithmException | InvalidKeyException ex) {
LogManager.getLogger(PoloniexTradingAPIClient.class).warn("Call to Poloniex Trading API resulted in exception - " + ex.getMessage(), ex);
}
return null;
}
/**
* Computes the HMAC hash of a given byte[]. This is a wrapper over the Mac crypto functions.
* @param data byte[] of content to hash
* @param key secret key to salt the hash
* @param hashType determines which alogirthm to use. The recommendation is to use HMAC-SHA256
* @return a byte[] presenting the HMAC hash of the source data.
*/
public static byte[] computeKeyedHash(byte[] data, String key, KeyedHashAlgorithm hashType) {
if (data == null || key == null) return null;
try {
Mac mac = Mac.getInstance(hashType.getAlgorithm());
mac.init(new SecretKeySpec(key.getBytes(), hashType.getAlgorithm()));
return mac.doFinal(data);
} catch (Exception e) {
throw new IllegalArgumentException("This should never happen!", e);
}
}
/***
* Computes RFC 2104-compliant HMAC signature. This can be used to sign the Amazon S3
* request urls
*
* @param data The data to be signed.
* @param key The signing key.
* @return The Base64-encoded RFC 2104-compliant HMAC signature.
* @throws java.security.SignatureException when signature generation fails
*/
public static String getHMac(String data, String key) throws SignatureException {
if (data == null) {
throw new NullPointerException("Data to be signed cannot be null");
}
String result = null;
try {
final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
// 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 &
// initialize with the signing key
Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
mac.init(signingKey);
// compute the hmac on input data bytes
byte[] digest = mac.doFinal(data.getBytes());
if (digest != null) {
// Base 64 Encode the results
result = Base64.encodeToString(digest, Base64.NO_WRAP);
}
} catch (Exception e) {
throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
}
return result;
}
private static Mac getMacForPassphrase(String passphrase, byte[] salt, int iterations)
throws GeneralSecurityException {
SecretKey key = getKeyFromPassphrase(passphrase, salt, iterations);
byte[] pbkdf2 = key.getEncoded();
SecretKeySpec hmacKey = new SecretKeySpec(pbkdf2, "HmacSHA1");
Mac hmac = Mac.getInstance("HmacSHA1");
hmac.init(hmacKey);
return hmac;
}
private static Triple<byte[], byte[], Mac> GetAlgorithmParameters(String algorithm, byte[] key) throws InvalidKeyException, NoSuchAlgorithmException {
byte[] aes_key;
byte[] hmac_key;
Mac hmac;
if (algorithm.equalsIgnoreCase(Aes128CbcHmacSha256.ALGORITHM_NAME)) {
if ((key.length << 3) < 256) {
throw new IllegalArgumentException(String.format("%s key length in bits %d < 256", algorithm, key.length << 3));
}
hmac_key = new byte[128 >> 3];
aes_key = new byte[128 >> 3];
// The HMAC key precedes the AES key
System.arraycopy(key, 0, hmac_key, 0, 128 >> 3);
System.arraycopy(key, 128 >> 3, aes_key, 0, 128 >> 3);
hmac = Mac.getInstance("HmacSHA256");
hmac.init(new SecretKeySpec(hmac_key, "HmacSHA256"));
} else if (algorithm.equalsIgnoreCase(Aes192CbcHmacSha384.ALGORITHM_NAME)) {
if ((key.length << 3) < 384) {
throw new IllegalArgumentException(String.format("%s key length in bits %d < 384", algorithm, key.length << 3));
}
hmac_key = new byte[192 >> 3];
aes_key = new byte[192 >> 3];
// The HMAC key precedes the AES key
System.arraycopy(key, 0, hmac_key, 0, 192 >> 3);
System.arraycopy(key, 192 >> 3, aes_key, 0, 192 >> 3);
hmac = Mac.getInstance("HmacSHA384");
hmac.init(new SecretKeySpec(hmac_key, "HmacSHA384"));
} else if (algorithm.equalsIgnoreCase(Aes256CbcHmacSha512.ALGORITHM_NAME)) {
if ((key.length << 3) < 512) {
throw new IllegalArgumentException(String.format("%s key length in bits %d < 512", algorithm, key.length << 3));
}
hmac_key = new byte[256 >> 3];
aes_key = new byte[256 >> 3];
// The HMAC key precedes the AES key
System.arraycopy(key, 0, hmac_key, 0, 256 >> 3);
System.arraycopy(key, 256 >> 3, aes_key, 0, 256 >> 3);
hmac = Mac.getInstance("HmacSHA512");
hmac.init(new SecretKeySpec(hmac_key, "HmacSHA512"));
} else {
throw new IllegalArgumentException(String.format("Unsupported algorithm: %s", algorithm));
}
return Triple.of(aes_key, hmac_key, hmac);
}
public static byte[] generateMac(byte[] byteCipherText, SecretKey integrityKey) throws NoSuchAlgorithmException, InvalidKeyException {
Mac sha256_HMAC = Mac.getInstance(HMAC_ALGORITHM);
sha256_HMAC.init(integrityKey);
return sha256_HMAC.doFinal(byteCipherText);
}
private boolean verifyRequest(final Map<String, Object[]> requestParameters) {
try {
String apiKey = null;
String secretKey = null;
String signature = null;
String unsignedRequest = null;
// - build a request string with sorted params, make sure it's all lowercase
// - sign the request, verify the signature is the same
final List<String> parameterNames = new ArrayList<>();
for (final Object paramNameObj : requestParameters.keySet()) {
parameterNames.add((String) paramNameObj); // put the name in a list that we'll sort later
}
Collections.sort(parameterNames);
for (final String paramName : parameterNames) {
// parameters come as name/value pairs in the form String/String[]
final String paramValue = ((String[]) requestParameters.get(paramName))[0];
if ("signature".equalsIgnoreCase(paramName)) {
signature = paramValue;
} else {
if ("apikey".equalsIgnoreCase(paramName)) {
apiKey = paramValue;
}
if (unsignedRequest == null) {
unsignedRequest = paramName + "=" + URLEncoder.encode(paramValue, "UTF-8").replaceAll("\\+", "%20");
} else {
unsignedRequest = unsignedRequest + "&" + paramName + "=" + URLEncoder.encode(paramValue, "UTF-8").replaceAll("\\+", "%20");
}
}
}
// if api/secret key are passed to the parameters
if ((signature == null) || (apiKey == null)) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("expired session, missing signature, or missing apiKey -- ignoring request...sig: " + signature + ", apiKey: " + apiKey);
}
return false; // no signature, bad request
}
final TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.CLOUD_DB);
txn.close();
User user = null;
// verify there is a user with this api key
final Pair<User, Account> userAcctPair = _accountMgr.findUserByApiKey(apiKey);
if (userAcctPair == null) {
s_logger.debug("apiKey does not map to a valid user -- ignoring request, apiKey: " + apiKey);
return false;
}
user = userAcctPair.first();
final Account account = userAcctPair.second();
if (!user.getState().equals(Account.State.enabled) || !account.getState().equals(Account.State.enabled)) {
s_logger.debug("disabled or locked user accessing the api, userid = " + user.getId() + "; name = " + user.getUsername() + "; state: " + user.getState() +
"; accountState: " + account.getState());
return false;
}
// verify secret key exists
secretKey = user.getSecretKey();
if (secretKey == null) {
s_logger.debug("User does not have a secret key associated with the account -- ignoring request, username: " + user.getUsername());
return false;
}
unsignedRequest = unsignedRequest.toLowerCase();
final Mac mac = Mac.getInstance("HmacSHA1");
final SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1");
mac.init(keySpec);
mac.update(unsignedRequest.getBytes());
final byte[] encryptedBytes = mac.doFinal();
final String computedSignature = Base64.encodeBase64String(encryptedBytes);
final boolean equalSig = ConstantTimeComparator.compareStrings(signature, computedSignature);
if (!equalSig) {
s_logger.debug("User signature: " + signature + " is not equaled to computed signature: " + computedSignature);
}
if (equalSig) {
requestParameters.put("userid", new Object[]{String.valueOf(user.getId())});
requestParameters.put("account", new Object[]{account.getAccountName()});
requestParameters.put("accountobj", new Object[]{account});
}
return equalSig;
} catch (final Exception ex) {
s_logger.error("unable to verifty request signature", ex);
}
return false;
}