Java Code Examples for javax.crypto.Mac#getInstance()

The following examples show how to use javax.crypto.Mac#getInstance() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Sign.java    From tencentcloud-sdk-java with Apache License 2.0 6 votes vote down vote up
public static String sign(String secretKey, String sigStr, String sigMethod)
    throws TencentCloudSDKException {
  String sig = null;
  try {
    Mac mac = Mac.getInstance(sigMethod);
    byte[] hash;
    SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(UTF8), mac.getAlgorithm());

    mac.init(secretKeySpec);
    hash = mac.doFinal(sigStr.getBytes(UTF8));
    sig = DatatypeConverter.printBase64Binary(hash);
  } catch (Exception e) {
    throw new TencentCloudSDKException(e.getClass().getName() + "-" + e.getMessage());
  }
  return sig;
}
 
Example 2
Source File: RobotConfigModel.java    From dingtalk-plugin with MIT License 6 votes vote down vote up
/**
 * 签名方法
 *
 * @return 签名
 */
private static String createSign(long timestamp, String secret) {
  String result = "";
  try {
    String seed = timestamp + "\n" + secret;
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
    byte[] signData = mac.doFinal(seed.getBytes(StandardCharsets.UTF_8));
    result = URLEncoder
        .encode(
            new String(Base64.encodeBase64(signData),
                StandardCharsets.UTF_8.name()
            ),
            StandardCharsets.UTF_8.name());
  } catch (NoSuchAlgorithmException | UnsupportedEncodingException | InvalidKeyException e) {
    log.error(e);
  }
  return result;
}
 
Example 3
Source File: HmacField.java    From outbackcdx with Apache License 2.0 6 votes vote down vote up
public HmacField(String algorithm, String messageTemplate, String fieldTemplate, String key, int expiresSecs) {
    this.algorithm = algorithm;
    this.messageTemplate = messageTemplate;
    this.fieldTemplate = fieldTemplate;
    this.key = key;
    this.expiresSecs = expiresSecs;

    // detect if algorithm is a Mac or MessageDigest
    try {
        Mac.getInstance(algorithm);
    } catch (NoSuchAlgorithmException e) {
        try {
            MessageDigest.getInstance(algorithm);
            useDigest = true;
        } catch (NoSuchAlgorithmException ex) {
            throw new RuntimeException(ex);
        }
    }

    validateConfig();
}
 
Example 4
Source File: IntegrityHmac.java    From JDKSourceCode1.8 with MIT License 6 votes vote down vote up
/**
 * Method IntegrityHmac
 *
 * @throws XMLSignatureException
 */
public IntegrityHmac() throws XMLSignatureException {
    String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI());
    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Created IntegrityHmacSHA1 using " + algorithmID);
    }

    try {
        this.macAlgorithm = Mac.getInstance(algorithmID);
    } catch (java.security.NoSuchAlgorithmException ex) {
        Object[] exArgs = { algorithmID, ex.getLocalizedMessage() };

        throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs);
    }
}
 
Example 5
Source File: IntegrityHmac.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Method IntegrityHmac
 *
 * @throws XMLSignatureException
 */
public IntegrityHmac() throws XMLSignatureException {
    String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI());
    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Created IntegrityHmacSHA1 using " + algorithmID);
    }

    try {
        this.macAlgorithm = Mac.getInstance(algorithmID);
    } catch (java.security.NoSuchAlgorithmException ex) {
        Object[] exArgs = { algorithmID, ex.getLocalizedMessage() };

        throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs);
    }
}
 
Example 6
Source File: HmacSha1Signature.java    From mdw with Apache License 2.0 5 votes vote down vote up
public static String getHMACHexdigestSignature (byte[] payloadBytes, String key)
throws InvalidKeyException, NoSuchAlgorithmException {
    SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), ALGORITHM);
    Mac mac = Mac.getInstance(ALGORITHM);
    mac.init(keySpec);
    byte[] rawHmac = mac.doFinal(payloadBytes);
    return Hex.encodeHexString(rawHmac);
}
 
Example 7
Source File: IntegrityHmac.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Proxy method for {@link java.security.Signature#initVerify(java.security.PublicKey)}
 * which is executed on the internal {@link java.security.Signature} object.
 *
 * @param secretKey
 * @throws XMLSignatureException
 */
protected void engineInitVerify(Key secretKey) throws XMLSignatureException {
    if (!(secretKey instanceof SecretKey)) {
        String supplied = secretKey.getClass().getName();
        String needed = SecretKey.class.getName();
        Object exArgs[] = { supplied, needed };

        throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
    }

    try {
        this.macAlgorithm.init(secretKey);
    } catch (InvalidKeyException ex) {
        // reinstantiate Mac object to work around bug in JDK
        // see: http://bugs.sun.com/view_bug.do?bug_id=4953555
        Mac mac = this.macAlgorithm;
        try {
            this.macAlgorithm = Mac.getInstance(macAlgorithm.getAlgorithm());
        } catch (Exception e) {
            // this shouldn't occur, but if it does, restore previous Mac
            if (log.isLoggable(java.util.logging.Level.FINE)) {
                log.log(java.util.logging.Level.FINE, "Exception when reinstantiating Mac:" + e);
            }
            this.macAlgorithm = mac;
        }
        throw new XMLSignatureException("empty", ex);
    }
}
 
Example 8
Source File: Des3DkCrypto.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
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);
}
 
Example 9
Source File: MessageHandler.java    From protect with MIT License 5 votes vote down vote up
public MessageHandler(String macAlgorithm) {
	try {
		// this.cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
		this.mac = Mac.getInstance(macAlgorithm);
	} catch (NoSuchAlgorithmException /* | NoSuchPaddingException */ ex) {
		ex.printStackTrace();
	}
}
 
Example 10
Source File: EncryptUtils.java    From DevUtils with Apache License 2.0 5 votes vote down vote up
/**
 * Hmac 加密模版方法
 * @param data      待加密数据
 * @param key       密钥
 * @param algorithm 算法
 * @return 指定加密算法和密钥, 加密后的数据
 */
public static byte[] hmacTemplate(final byte[] data, final byte[] key, final String algorithm) {
    if (data == null || data.length == 0 || key == null || key.length == 0) return null;
    try {
        SecretKeySpec secretKey = new SecretKeySpec(key, algorithm);
        Mac mac = Mac.getInstance(algorithm);
        mac.init(secretKey);
        return mac.doFinal(data);
    } catch (Exception e) {
        JCLogUtils.eTag(TAG, e, "hmacTemplate");
        return null;
    }
}
 
Example 11
Source File: CommonUtil.java    From pe-protector-moe with GNU General Public License v3.0 5 votes vote down vote up
public static String encryptionHMAC(String source) {
    try {
        SecretKey secretKey = new SecretKeySpec(Config.key.getBytes(ENCODING), MAC_NAME);
        Mac mac = Mac.getInstance(MAC_NAME);
        mac.init(secretKey);
        mac.update(source.getBytes(ENCODING));
        byte[] b = mac.doFinal();
        return Base64.encodeToString(b, 2);
    } catch (Exception e) {
        return null;
    }
}
 
Example 12
Source File: Cryptos.java    From Shop-for-JavaWeb with MIT License 5 votes vote down vote up
/**
 * 使用HMAC-SHA1进行消息签名, 返回字节数组,长度为20字节.
 * 
 * @param input 原始输入字符数组
 * @param key HMAC-SHA1密钥
 */
public static byte[] hmacSha1(byte[] input, byte[] key) {
	try {
		SecretKey secretKey = new SecretKeySpec(key, HMACSHA1);
		Mac mac = Mac.getInstance(HMACSHA1);
		mac.init(secretKey);
		return mac.doFinal(input);
	} catch (GeneralSecurityException e) {
		throw Exceptions.unchecked(e);
	}
}
 
Example 13
Source File: WXPayUtil.java    From common-project with Apache License 2.0 5 votes vote down vote up
/**
 * 生成 HMACSHA256
 * @param data 待处理数据
 * @param key 密钥
 * @return 加密结果
 * @throws Exception
 */
public static String HMACSHA256(String data, String key) throws Exception {
    Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
    SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
    sha256_HMAC.init(secret_key);
    byte[] array = sha256_HMAC.doFinal(data.getBytes("UTF-8"));
    StringBuilder sb = new StringBuilder();
    for (byte item : array) {
        sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
    }
    return sb.toString().toUpperCase();
}
 
Example 14
Source File: AsymmetricMasterCipher.java    From Silence with GNU General Public License v3.0 5 votes vote down vote up
private byte[] getDigestedBytes(byte[] secretBytes, int iteration) {
  try {
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(new SecretKeySpec(secretBytes, "HmacSHA256"));
    return mac.doFinal(Conversions.intToByteArray(iteration));
  } catch (NoSuchAlgorithmException | java.security.InvalidKeyException e) {
    throw new AssertionError(e);
  }
}
 
Example 15
Source File: MD5Util.java    From jee-universal-bms with Apache License 2.0 5 votes vote down vote up
public static String hmacMd5Hex(String signingKey, String stringToSign) {
	try {
		Mac mac = Mac.getInstance(KEY_MAC);
           mac.init(new SecretKeySpec(signingKey.getBytes(DEFAULT_CHARSET), KEY_MAC));
           byte[] result = mac.doFinal(stringToSign.getBytes(DEFAULT_CHARSET));
           return Encodes.encodeHex(result);
	} catch (Exception ex) {
	}
	return null;
}
 
Example 16
Source File: CSRFHandlerImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
public CSRFHandlerImpl(final Vertx vertx, final String secret) {
  try {
    random = VertxContextPRNG.current(vertx);
    mac = Mac.getInstance("HmacSHA256");
    mac.init(new SecretKeySpec(secret.getBytes(), "HmacSHA256"));
  } catch (NoSuchAlgorithmException | InvalidKeyException e) {
    throw new RuntimeException(e);
  }
}
 
Example 17
Source File: CryptoTools.java    From thundernetwork with GNU Affero General Public License v3.0 5 votes vote down vote up
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;
}
 
Example 18
Source File: OAuthUtils.java    From flickr-uploader with GNU General Public License v2.0 5 votes vote down vote up
public static String hmacsha1(String data, String key, String tokenSecret) throws IllegalStateException, UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
	byte[] byteHMAC = null;
	Mac mac = Mac.getInstance(HMAC_SHA1);
	if (tokenSecret == null) {
		tokenSecret = "";
	}
	SecretKeySpec spec = new SecretKeySpec((key + PARAMETER_SEPARATOR + tokenSecret).getBytes(), HMAC_SHA1);
	mac.init(spec);
	byteHMAC = mac.doFinal(data.getBytes(ENC));

	return new String(Base64.encode(byteHMAC));
}
 
Example 19
Source File: PBMacDoFinalVsUpdate.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Uses a random generator to initialize a message, instantiate a Mac object
 * according to the given PBMAC1 algorithm, initialize the object with a
 * SecretKey derived using PBKDF2 algorithm (see PKCS #5 v21, chapter 7.1),
 * feed the message into the Mac object all at once and get the output MAC
 * as result1. Reset the Mac object, chop the message into three pieces,
 * feed into the Mac object sequentially, and get the output MAC as result2.
 * Finally, compare result1 and result2 and see if they are the same.
 *
 * @param theMacAlgo PBMAC algorithm to test
 * @param thePBKDF2Algo PBKDF2 algorithm to test
 * @return true - the test is passed; false - otherwise.
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws InvalidKeySpecException
 */
protected boolean doTest(String theMacAlgo, String thePBKDF2Algo)
        throws NoSuchAlgorithmException, InvalidKeyException,
        InvalidKeySpecException {
    int OFFSET = 5;

    // Some message for which a MAC result will be calculated
    byte[] plain = new byte[25];
    new SecureRandom().nextBytes(plain);

    // Form tail - is one of the three pieces
    byte[] tail = new byte[plain.length - OFFSET];
    System.arraycopy(plain, OFFSET, tail, 0, tail.length);

    // Obtain a SecretKey using PBKDF2
    SecretKey key = getSecretKey(thePBKDF2Algo);

    // Instantiate Mac object and init it with a SecretKey and calc result1
    Mac theMac = Mac.getInstance(theMacAlgo);
    theMac.init(key);
    byte[] result1 = theMac.doFinal(plain);

    if (!isMacLengthExpected(theMacAlgo, result1.length)) {
        return false;
    }

    // Reset Mac and calculate result2
    theMac.reset();
    theMac.update(plain[0]);
    theMac.update(plain, 1, OFFSET - 1);
    byte[] result2 = theMac.doFinal(tail);

    // Return result
    if (!java.util.Arrays.equals(result1, result2)) {
        System.out.println("result1 and result2 are not the same:");
        System.out.println("result1: " + dumpByteArray(result1));
        System.out.println("result2: " + dumpByteArray(result2));
        return false;
    } else {
        System.out.println("Resulted MAC with update and doFinal is same");
    }

    return true;
}
 
Example 20
Source File: AwsSignatureV4.java    From cs-actions with Apache License 2.0 3 votes vote down vote up
/**
 * Calculates the keyed-hash message authentication code for the data string.
 *
 * @param data String for which the HMAC will be calculated.
 * @param key  Key used for HMAC calculation.
 * @return HMAC's bytes. This result is not encoded.
 */
private byte[] calculateHmacSHA256(String data, byte[] key)
        throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
    Mac mac = Mac.getInstance(HMAC_ALGORITHM);
    mac.init(new SecretKeySpec(key, HMAC_ALGORITHM));
    return mac.doFinal(data.getBytes(ENCODING));
}