javax.crypto.Mac#doFinal ( )源码实例Demo

下面列出了javax.crypto.Mac#doFinal ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: sakai   文件: HMAC_SHA1.java
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);
}
 
源代码2 项目: jdk8u_jdk   文件: PBMacBuffer.java
/**
 * 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;
}
 
源代码3 项目: arcusplatform   文件: RecordingSessionFactory.java
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");
   }
}
 
源代码4 项目: xifan   文件: XAuthUtils.java
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);
    }
}
 
源代码5 项目: joyrpc   文件: HmacSignature.java
@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);
}
 
源代码6 项目: sling-whiteboard   文件: TokenStore.java
/**
 * @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();
}
 
源代码7 项目: hasor   文件: HmacUdfSource.java
/** 使用 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);
}
 
源代码8 项目: dragonwell8_jdk   文件: LargeByteBufferTest.java
@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");
    }
}
 
源代码9 项目: ZTuoExchange_framework   文件: AliyunUtil.java
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;
}
 
源代码10 项目: android_9.0.0_r45   文件: SP800Derive.java
/**
 * 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();
}
 
源代码13 项目: thunder   文件: CryptoTools.java
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;
}
 
源代码14 项目: openjdk-jdk9   文件: Des3DkCrypto.java
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);
}
 
源代码15 项目: mumu   文件: HmacCoder.java
/**
 * 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);
}
 
源代码16 项目: qpid-broker-j   文件: SaslUtils.java
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();
}
 
源代码17 项目: mcg-helper   文件: TOTP.java
/**
 * 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);
    }
}
 
源代码18 项目: openjdk-jdk9   文件: LargeByteBufferTest.java
@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");
    }
}
 
源代码19 项目: AWSSigner   文件: Utility.java
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));
}
 
源代码20 项目: openjdk-jdk9   文件: PBMacBuffer.java
/**
 * 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;
}