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

The following examples show how to use javax.crypto.Mac#doFinal() . 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: HMAC_SHA1.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
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);
}
 
Example 2
Source File: XAuthUtils.java    From xifan with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example 3
Source File: RecordingSessionFactory.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
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");
   }
}
 
Example 4
Source File: PBMacBuffer.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 5
Source File: HmacUdfSource.java    From hasor with Apache License 2.0 5 votes vote down vote up
/** 使用 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);
}
 
Example 6
Source File: LargeByteBufferTest.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
@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");
    }
}
 
Example 7
Source File: AliyunUtil.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
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;
}
 
Example 8
Source File: SP800Derive.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example 9
Source File: HMACSha1SignatureService.java    From WoocommerceAndroidOAuth1 with MIT License 5 votes vote down vote up
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);
}
 
Example 10
Source File: TokenStore.java    From sling-whiteboard with Apache License 2.0 5 votes vote down vote up
/**
 * @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();
}
 
Example 11
Source File: HmacSignature.java    From joyrpc with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 12
Source File: DynamoDbSigner.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 13
Source File: CryptoTools.java    From thunder 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 14
Source File: Des3DkCrypto.java    From openjdk-jdk9 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 15
Source File: HmacCoder.java    From mumu with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example 16
Source File: SaslUtils.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 17
Source File: TOTP.java    From mcg-helper with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 18
Source File: LargeByteBufferTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@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");
    }
}
 
Example 19
Source File: Utility.java    From AWSSigner with MIT License 4 votes vote down vote up
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));
}
 
Example 20
Source File: PBMacBuffer.java    From openjdk-jdk9 with GNU General Public License v2.0 3 votes vote down vote up
/**
 * 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;
}