下面列出了javax.crypto.Mac#doFinal ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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);
}
/**
* Large ByteBuffer test case. Generate random ByteBuffer of LARGE_SIZE
* size. Performs MAC operation with the given Mac object (theMac
* parameter).Verifies the assertion "Upon return, the buffer's position
* will be equal to its limit; its limit will not have changed".
*
* @param theMac MAC object to test.
* @return true - test case passed; false - otherwise;
*/
protected boolean largeByteBufferTest(Mac theMac) {
ByteBuffer buf = generateRandomByteBuffer(LARGE_SIZE);
int limitBefore = buf.limit();
theMac.update(buf);
theMac.doFinal();
int limitAfter = buf.limit();
int positonAfter = buf.position();
if (limitAfter != limitBefore) {
System.out.println("FAIL: Buffer's limit has been chenged.");
return false;
}
if (positonAfter != limitAfter) {
System.out.println("FAIL: "
+ "Buffer's position isn't equal to its limit");
return false;
}
return true;
}
private static void verifySignature(SecretKeySpec secret, UUID cameraId, UUID accountId, UUID placeId, UUID personId, UUID recordingId, ByteBuf sig) throws Exception {
StringBuilder message = new StringBuilder(180);
message.append(cameraId);
message.append(accountId);
message.append(placeId);
message.append(personId);
message.append(recordingId);
Mac hmac = Mac.getInstance("HmacSHA256");
hmac.init(secret);
byte[] result = hmac.doFinal(message.toString().getBytes(StandardCharsets.UTF_8));
ByteBuf computed = Unpooled.wrappedBuffer(result, 0, 16);
if (!ByteBufUtil.equals(sig,computed)) {
RECORDING_SESSION_CREATE_VALIDATION.inc();
throw new Exception("signature validation failed");
}
}
private static String doSign(String baseString) {
String apiSecret = Constants.FanFou.CONSUMER_SECRET;
String tokenSecret = Constants.FanFou.OAUTH_TOKENSECRET;
String keyString = OAuthEncoder.encode(apiSecret) + '&';
if (tokenSecret != null) {
keyString += OAuthEncoder.encode(tokenSecret);
}
try {
SecretKeySpec key = new SecretKeySpec(keyString.getBytes(CHARSET), HMAC_SHA1);
Mac mac = Mac.getInstance(HMAC_SHA1);
mac.init(key);
byte[] bytes = mac.doFinal(baseString.getBytes(CHARSET));
return bytesToBase64String(bytes).replace(CARRIAGE_RETURN, EMPTY_STRING);
} catch (Exception e) {
e.printStackTrace();
Logger.e("doSign error:" + e.getMessage());
throw new RuntimeException(e);
}
}
@Override
public byte[] encrypt(final byte[] source, final byte[] key) throws GeneralSecurityException {
//根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
SecretKeySpec signinKey = new SecretKeySpec(key, hmacType);
//生成一个指定 Mac 算法 的 Mac 对象
Mac mac = Mac.getInstance(hmacType);
//用给定密钥初始化 Mac 对象
mac.init(signinKey);
//完成 Mac 操作
return mac.doFinal(source);
}
/**
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws UnsupportedEncodingException
* @throws IllegalStateException
* @throws NullPointerException if <code>tokenFile</code> is
* <code>null</code>.
*/
TokenStore(final File tokenFile, final long sessionTimeout,
final boolean fastSeed) throws NoSuchAlgorithmException,
InvalidKeyException, IllegalStateException,
UnsupportedEncodingException {
if (tokenFile == null) {
throw new NullPointerException("tokenfile");
}
this.random = SecureRandom.getInstance(SHA1PRNG);
this.ttl = sessionTimeout;
this.tokenFile = tokenFile;
this.tmpTokenFile = new File(tokenFile + ".tmp");
// prime the secret keys from persistence
loadTokens();
// warm up the crypto API
if (fastSeed) {
random.setSeed(getFastEntropy());
} else {
log.info("Seeding the secure random number generator can take "
+ "up to several minutes on some operating systems depending "
+ "upon environment factors. If this is a problem for you, "
+ "set the system property 'java.security.egd' to "
+ "'file:/dev/./urandom' or enable the Fast Seed Generator "
+ "in the Web Console");
}
byte[] b = new byte[20];
random.nextBytes(b);
final SecretKey secretKey = new SecretKeySpec(b, HMAC_SHA1);
final Mac m = Mac.getInstance(HMAC_SHA1);
m.init(secretKey);
m.update(UTF_8.getBytes(UTF_8));
m.doFinal();
}
/** 使用 HMAC-SHA1 签名方法对 content 进行签名 */
public static String hmacSHA1_string(String signKey, String content) throws NoSuchAlgorithmException, InvalidKeyException {
Mac mac = Mac.getInstance(SignType.HmacSHA1.getSignType());//Mac 算法对象
mac.init(new SecretKeySpec(signKey.getBytes(), SignType.HmacSHA1.getSignType()));//初始化 Mac 对象
byte[] rawHmac = mac.doFinal(content.getBytes());
return Base64.getEncoder().encodeToString(rawHmac);
}
@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 data, String key) {
String result;
try {
SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(signingKey);
byte[] rawHmac = mac.doFinal(data.getBytes());
result = (new BASE64Encoder()).encode(rawHmac);
} catch (Exception e) {
throw new Error("Failed to generate HMAC : " + e.getMessage());
}
return result;
}
/**
* Generate output from a label and context. We add a length field at the end of the context to
* disambiguate it from the length even in the presence of zero bytes.
*/
public byte[] withContext(byte[] label, byte[] context) {
final Mac m = getMac();
// Hardwired counter value: 1
update32(m, 1); // Hardwired counter value
m.update(label);
m.update((byte) 0);
m.update(context);
update32(m, context.length * 8); // Disambiguate context
update32(m, 256); // Hardwired output length
return m.doFinal();
}
private String doSign(String toSign, String keyString) throws Exception
{
Log.d("is it signing","----------------------"+toSign);
Log.d("is 22222222",keyString+"");
SecretKeySpec key = new SecretKeySpec((keyString).getBytes(UTF8), HMAC_SHA1);
Mac mac = Mac.getInstance(HMAC_SHA1);
mac.init(key);
byte[] bytes = mac.doFinal(toSign.getBytes(UTF8));
return bytesToBase64String(bytes).replace(CARRIAGE_RETURN, EMPTY_STRING);
}
byte[] calculateSignature(Map<String, AttributeValue> itemAttributes,
Map<String, Set<EncryptionFlags>> attributeFlags, byte[] associatedData,
SecretKey key) throws GeneralSecurityException {
if (key instanceof DelegatedKey) {
return calculateSignature(itemAttributes, attributeFlags, associatedData, (DelegatedKey)key);
}
byte[] stringToSign = calculateStringToSign(itemAttributes, attributeFlags, associatedData);
Mac hmac = Mac.getInstance(key.getAlgorithm());
hmac.init(key);
hmac.update(stringToSign);
return hmac.doFinal();
}
public static byte[] addHMAC (byte[] data, byte[] keyBytes) throws NoSuchAlgorithmException, InvalidKeyException {
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(keySpec);
byte[] result = mac.doFinal(data);
byte[] total = new byte[result.length + data.length];
System.arraycopy(result, 0, total, 0, result.length);
System.arraycopy(data, 0, total, result.length, data.length);
return total;
}
protected byte[] getHmac(byte[] key, byte[] msg)
throws GeneralSecurityException {
SecretKey keyKi = new SecretKeySpec(key, "HmacSHA1");
Mac m = Mac.getInstance("HmacSHA1");
m.init(keyKi);
return m.doFinal(msg);
}
/**
* HmacSHA1加密
*
* @param data 待加密数据
* @param key 密钥
* @return byte[] 消息摘要
* @throws Exception
*/
public static byte[] encodeHmacSHA(byte[] data, byte[] key) throws Exception {
// 还原密钥
SecretKey secretKey = new SecretKeySpec(key, "HMacTiger");
// 实例化Mac SslMacMD5
Mac mac = Mac.getInstance("SslMacMD5");// secretKey.getAlgorithm());
// 初始化Mac
mac.init(secretKey);
// 执行消息摘要
return mac.doFinal(data);
}
public static byte[] generateCramMD5ClientResponse(String userName, String userPassword, byte[] challengeBytes)
throws Exception
{
String macAlgorithm = "HmacMD5";
Mac mac = Mac.getInstance(macAlgorithm);
mac.init(new SecretKeySpec(userPassword.getBytes(StandardCharsets.UTF_8), macAlgorithm));
final byte[] messageAuthenticationCode = mac.doFinal(challengeBytes);
String responseAsString = userName + " " + toHex(messageAuthenticationCode);
return responseAsString.getBytes();
}
/**
* This method uses the JCE to provide the crypto algorithm.
* HMAC computes a Hashed Message Authentication Code with the
* crypto hash algorithm as a parameter.
*
* @param crypto: the crypto algorithm (HmacSHA1, HmacSHA256,
* HmacSHA512)
* @param keyBytes: the bytes to use for the HMAC key
* @param text: the message or text to be authenticated
*/
private static byte[] hmac_sha(String crypto, byte[] keyBytes,
byte[] text){
try {
Mac hmac;
hmac = Mac.getInstance(crypto);
SecretKeySpec macKey =
new SecretKeySpec(keyBytes, "RAW");
hmac.init(macKey);
return hmac.doFinal(text);
} catch (GeneralSecurityException gse) {
throw new UndeclaredThrowableException(gse);
}
}
@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");
}
}
private static byte[] HmacSHA256(String data, byte[] key) throws Exception {
String algorithm="HmacSHA256";
Mac mac = Mac.getInstance(algorithm);
mac.init(new SecretKeySpec(key, algorithm));
return mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
}
/**
* Empty ByteBuffer test case. Generates an empty ByteBuffer. Perform MAC
* operation. No exceptions are expected.
*
* @param theMac
* @return true - test case pass; exception otherwise
*/
protected boolean emptyByteBufferTest(Mac theMac) {
ByteBuffer buf = generateRandomByteBuffer(0);
theMac.update(buf);
theMac.doFinal();
return true;
}