Java 类javax.crypto.Mac 实例源码

项目:jdk8u-jdk    文件:MacKAT.java   
@Override
public void run(Provider p) throws Exception {
    Mac mac = Mac.getInstance(alg, p);
    SecretKey keySpec = new SecretKeySpec(key, alg);
    mac.init(keySpec);
    mac.update(input);
    byte[] macv = mac.doFinal();
    if (Arrays.equals(macvalue, macv) == false) {
        System.out.println("Mac test for " + alg + " failed:");
        if (input.length < 256) {
            System.out.println("input:       "
                    + PKCS11Test.toString(input));
        }
        System.out.println("key:        " + PKCS11Test.toString(key));
        System.out.println("macvalue:   "
                + PKCS11Test.toString(macvalue));
        System.out.println("calculated: " + PKCS11Test.toString(macv));
        throw new Exception("Mac test for " + alg + " failed");
    }
    System.out.println("passed: " + alg);
}
项目:libcwfincore    文件:GdaxExchangeSession.java   
private String computeAccessSignature(String timestamp, HttpMethod method, String urlTxt, ByteBuffer body)
        throws GeneralSecurityException {
    if (conn == null) {
        throw new IllegalStateException("cannot generate exchange request post-disconnect()");
    }

    String prehash = timestamp + method.name() + urlTxt;

    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(signingKey);
    mac.update(prehash.getBytes());
    if (body != null) {
        mac.update(body);
    }
    return new String(Base64.encodeBase64(mac.doFinal()));
}
项目:gplaymusic    文件:Signable.java   
protected Signature createSignature(String id) {
  try {
    SecretKeySpec singingkey = new SecretKeySpec(key, "HmacSHA1");
    Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(singingkey);
    String slt = String.valueOf(System.currentTimeMillis() * 1000);
    byte[] value = (id + slt).getBytes("UTF-8");
    byte[] sigBytes = mac.doFinal(value);
    byte[] fullSig = Base64.getUrlEncoder().encode(sigBytes);
    byte[] shortened = Arrays.copyOf(fullSig, fullSig.length - 1);
    String sig = new String(shortened, "UTF-8");
    return new Signature(sig, slt);
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
项目:OpenJSharp    文件:AesDkCrypto.java   
/**
 * 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;
}
项目:wolfcrypt-jni    文件:WolfCryptMacTest.java   
@Test
public void testGetMacFromProvider()
    throws NoSuchProviderException, NoSuchAlgorithmException {

    Mac mac;

    /* try to get all available options we expect to have */
    for (int i = 0; i < wolfJCEAlgos.length; i++) {
        mac = Mac.getInstance(wolfJCEAlgos[i], "wolfJCE");
    }

    /* getting a garbage algorithm should throw an exception */
    try {
        mac = Mac.getInstance("NotValid", "wolfJCE");

        fail("Mac.getInstance should throw NoSuchAlgorithmException " +
             "when given bad algorithm value");

    } catch (NoSuchAlgorithmException e) { }
}
项目:openjdk-jdk10    文件: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;
}
项目:OpenJSharp    文件:DOMHMACSignatureMethod.java   
byte[] sign(Key key, SignedInfo si, XMLSignContext context)
    throws InvalidKeyException, XMLSignatureException
{
    if (key == null || si == null) {
        throw new NullPointerException();
    }
    if (!(key instanceof SecretKey)) {
        throw new InvalidKeyException("key must be SecretKey");
    }
    if (hmac == null) {
        try {
            hmac = Mac.getInstance(getJCAAlgorithm());
        } catch (NoSuchAlgorithmException nsae) {
            throw new XMLSignatureException(nsae);
        }
    }
    if (outputLengthSet && outputLength < getDigestLength()) {
        throw new XMLSignatureException
            ("HMACOutputLength must not be less than " + getDigestLength());
    }
    hmac.init((SecretKey)key);
    ((DOMSignedInfo)si).canonicalize(context, new MacOutputStream(hmac));
    return hmac.doFinal();
}
项目:QiNiuTest    文件:Auth.java   
/**
 * 生成HTTP请求签名字符串
 *
 * @param urlString
 * @param body
 * @param contentType
 * @return
 */
public String signRequest(String urlString, byte[] body, String contentType) {
    URI uri = URI.create(urlString);
    String path = uri.getRawPath();
    String query = uri.getRawQuery();

    Mac mac = createMac();

    mac.update(StringUtils.utf8Bytes(path));

    if (query != null && query.length() != 0) {
        mac.update((byte) ('?'));
        mac.update(StringUtils.utf8Bytes(query));
    }
    mac.update((byte) '\n');
    if (body != null && body.length > 0 && !StringUtils.isNullOrEmpty(contentType)) {
        if (contentType.equals(Client.FormMime)
                || contentType.equals(Client.JsonMime)) {
            mac.update(body);
        }
    }

    String digest = UrlSafeBase64.encodeToString(mac.doFinal());

    return this.accessKey + ":" + digest;
}
项目:FirefoxData-android    文件:HKDF.java   
public static byte[] hkdfExpand(byte[] prk, byte[] info, int len) throws NoSuchAlgorithmException, InvalidKeyException {
  Mac hmacHasher = makeHMACHasher(prk);

  byte[] T  = {};
  byte[] Tn = {};

  int iterations = (int) Math.ceil(((double)len) / (BLOCKSIZE));
  for (int i = 0; i < iterations; i++) {
    Tn = digestBytes(Utils.concatAll(Tn, info, Utils.hex2Byte(Integer.toHexString(i + 1))),
                     hmacHasher);
    T = Utils.concatAll(T, Tn);
  }

  byte[] result = new byte[len];
  System.arraycopy(T, 0, result, 0, len);
  return result;
}
项目:Android_Code_Arbiter    文件:GoogleMapsSigUtil.java   
public String signRequest(String path, String query) throws NoSuchAlgorithmException,
        InvalidKeyException, UnsupportedEncodingException, URISyntaxException {

    // Retrieve the proper URL components to sign
    String resource = path + '?' + query;

    // Get an HMAC-SHA1 signing key from the raw key bytes
    SecretKeySpec sha1Key = new SecretKeySpec(key, "HmacSHA1");

    // Get an HMAC-SHA1 Mac instance and initialize it with the HMAC-SHA1 key
    Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(sha1Key);

    // compute the binary signature for the request
    byte[] sigBytes = mac.doFinal(resource.getBytes());

    // base 64 encode the binary signature
    String signature = Base64.encodeBytes(sigBytes);

    // convert the signature to 'web safe' base 64
    signature = signature.replace('+', '-');
    signature = signature.replace('/', '_');

    return resource + "&signature=" + signature;
}
项目:lams    文件: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);
}
项目:EasyAndroid    文件:EncryptTool.java   
/**
 * Hmac加密模板
 *
 * @param data      数据
 * @param key       秘钥
 * @param algorithm 加密算法
 * @return 密文字节数组
 */
private static byte[] hmacTemplate(byte[] data, byte[] key, 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(InvalidKeyException | NoSuchAlgorithmException e)
    {
        e.printStackTrace();
        return null;
    }
}
项目:Equella    文件:D2LSigner.java   
/**
 * Computes the hmacSha256 hash of the data using the key given
 * @param keyBytes The key to use to calculate the hash
 * @param dataBytes The data to use to calculate the hash
 * @return The hmacSha256 hash of the data using the key
 */
private static byte[] computeHash(byte[] keyBytes, byte[] dataBytes)
{
    try
    {
        Mac hmacSha256 = Mac.getInstance("HmacSHA256");
        SecretKeySpec key = new SecretKeySpec(keyBytes, "HmacSHA256");
        hmacSha256.init(key);
        byte[] b = hmacSha256.doFinal(dataBytes);

        return b;
    }
    catch( Exception e )
    {
        e.printStackTrace();
    }

    return null;
}
项目:openjdk-jdk10    文件:PBMacBuffer.java   
/**
 * Tests Mac.update(ByteBuffer input) method. Three test cases are
 * performed: - large ByteBuffer test case to test if the update() method
 * process a large ByteBuffer correctly; - empty ByteBuffer test case to
 * test if the update() method process an empty ByteBuffer correctly; - NULL
 * ByteBuffer test case to test if the update() method throws expected
 * IllegalArgumentException exception.
 *
 * @param theMacAlgo PBMAC algorithm to test
 * @param thePBKDF2Algo PBKDF2 algorithm to test
 * @return true - test passed; false - otherwise.
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws InvalidKeySpecException
 * @see javax.crypto.Mac
 */
protected boolean doTest(String theMacAlgo, String thePBKDF2Algo)
        throws NoSuchAlgorithmException, InvalidKeyException,
        InvalidKeySpecException {
    // obtain a SecretKey using PBKDF2
    SecretKey key = getSecretKey(thePBKDF2Algo);

    // Instantiate Mac object and init it with a SecretKey
    Mac theMac = Mac.getInstance(theMacAlgo);
    theMac.init(key);

    // Do large ByteBuffer test case
    if (!largeByteBufferTest(theMac)) {
        System.out.println("Large ByteBuffer test case failed.");
        return false;
    }

    // Do empty ByteBuffer test case
    if (!emptyByteBufferTest(theMac)) {
        System.out.println("Empty ByteBuffer test case failed.");
        return false;
    }

    // Do null ByteBuffer test case
    if (!nullByteBufferTest(theMac)) {
        System.out.println("NULL ByteBuffer test case failed.");
        return false;
    }

    return true;
}
项目:bittrex4j    文件:EncryptionUtility.java   
static String calculateHash(String secret, String url, String algorithm) throws InvalidKeyException, NoSuchAlgorithmException {
    Mac shaHmac = Mac.getInstance(algorithm);
    SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes(), algorithm);
    shaHmac.init(secretKey);
    byte[] hash = shaHmac.doFinal(url.getBytes());
    return Hex.encodeHexString(hash);
}
项目:BaseCore    文件:EncryptUtils.java   
/**
 * Hmac加密模板
 *
 * @param data      数据
 * @param key       秘钥
 * @param algorithm 加密算法
 * @return 密文字节数组
 */
private static byte[] hmacTemplate(byte[] data, byte[] key, 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 (InvalidKeyException | NoSuchAlgorithmException e) {
        e.printStackTrace();
        return null;
    }
}
项目:mumu    文件:HmacCoder.java   
/**
 * HmacSHA512加密
 * 
 * @param data 待加密数据
 * @param key 密钥
 * @return byte[] 消息摘要
 * @throws Exception
 */
public static byte[] encodeHmacSHA512(byte[] data, byte[] key) throws Exception {
    // 还原密钥
    SecretKey secretKey = new SecretKeySpec(key, "HmacSHA512");
    // 实例化Mac
    Mac mac = Mac.getInstance(secretKey.getAlgorithm());
    // 初始化Mac
    mac.init(secretKey);
    // 执行消息摘要
    return mac.doFinal(data);
}
项目:JwtDemo    文件:JwtApp.java   
private static String doHMACSHA256(String part1AndPart2, String secretKey) throws Exception {
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(new SecretKeySpec(secretKey.getBytes(), "HmacSHA256"));

    byte[] hashBytes = mac.doFinal(part1AndPart2.getBytes());
    String hash = doBASE64(hashBytes);
    return hash;
}
项目:mumu-core    文件:HmacCoder.java   
/**
 * HmacMD4消息摘要
 * 
 * @param data 待做消息摘要处理的数据
 * @param byte[] 密钥
 * @return byte[] 消息摘要
 * @throws Exception
 */
public static byte[] encodeHmacMD4(byte[] data, byte[] key) throws Exception {
    // 还原密钥
    SecretKey secretKey = new SecretKeySpec(key, "HmacMD4");
    // 实例化Mac
    Mac mac = Mac.getInstance(secretKey.getAlgorithm());
    // 初始化Mac
    mac.init(secretKey);
    // 执行消息摘要
    return mac.doFinal(data);
}
项目:googles-monorepo-demo    文件:MacHashFunctionTest.java   
public void testMultipleUpdates() throws Exception {
  Mac mac = Mac.getInstance("HmacSHA1");
  mac.init(SHA1_KEY);
  mac.update("hello".getBytes(UTF_8));
  mac.update("world".getBytes(UTF_8));

  assertEquals(
      HashCode.fromBytes(mac.doFinal()),
      Hashing.hmacSha1(SHA1_KEY).newHasher()
          .putString("hello", UTF_8)
          .putString("world", UTF_8)
          .hash());
}
项目:tumbviewer    文件:OAuth1SigningHelper.java   
private String getSignature(String key, String text) {
    try {
        SecretKey secretKey = new SecretKeySpec(key.getBytes(ENC), HMAC_SHA1);
        Mac mac = Mac.getInstance(HMAC_SHA1);
        mac.init(secretKey);
        byte[] result = mac.doFinal(text.getBytes(ENC));

        return Base64.encodeToString(result, Base64.NO_WRAP);
    } catch (UnsupportedEncodingException | NoSuchAlgorithmException | InvalidKeyException e) {
        return "";
    }
}
项目:aws-sdk-java-v2    文件:AbstractAwsSigner.java   
protected byte[] sign(byte[] data, byte[] key, SigningAlgorithm algorithm) throws SdkClientException {
    try {
        Mac mac = algorithm.getMac();
        mac.init(new SecretKeySpec(key, algorithm.toString()));
        return mac.doFinal(data);
    } catch (Exception e) {
        throw new SdkClientException(
                "Unable to calculate a request signature: "
                + e.getMessage(), e);
    }
}
项目:OpenJSharp    文件:IntegrityHmac.java   
/**
 * 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);
    }
}
项目:mumu    文件:HmacCoder.java   
/**
 * HmacMD5加密
 * 
 * @param data 待加密数据
 * @param key 密钥
 * @return byte[] 消息摘要
 * @throws Exception
 */
public static byte[] encodeHmacMD5(byte[] data, byte[] key) throws Exception {
    // 还原密钥
    SecretKey secretKey = new SecretKeySpec(key, "HmacMD5");
    // 实例化Mac "SslMacMD5"
    Mac mac = Mac.getInstance("SslMacMD5");// secretKey.getAlgorithm());
    // 初始化Mac
    mac.init(secretKey);
    // 执行消息摘要
    return mac.doFinal(data);
}
项目:googles-monorepo-demo    文件:MacHashFunction.java   
private static boolean supportsClone(Mac mac) {
  try {
    mac.clone();
    return true;
  } catch (CloneNotSupportedException e) {
    return false;
  }
}
项目:JAVA-    文件:HmacCoder.java   
/**
 * HmacSHA512加密
 * 
 * @param data 待加密数据
 * @param key 密钥
 * @return byte[] 消息摘要
 * @throws Exception
 */
public static byte[] encodeHmacSHA512(byte[] data, byte[] key) throws Exception {
    // 还原密钥
    SecretKey secretKey = new SecretKeySpec(key, "HmacSHA512");
    // 实例化Mac
    Mac mac = Mac.getInstance(secretKey.getAlgorithm());
    // 初始化Mac
    mac.init(secretKey);
    // 执行消息摘要
    return mac.doFinal(data);
}
项目:letv    文件:rcrrrr.java   
public static String bьь044Cь044Cь(String str, String str2) {
    try {
        byte[] bytes = str.getBytes(UrlUtils.UTF8);
        Mac instance = Mac.getInstance("HmacSHA256");
        instance.init(new SecretKeySpec(str2.getBytes(UrlUtils.UTF8), "HmacSHA256"));
        bytes = instance.doFinal(bytes);
        if (((bСССС04210421 + bС0421СС04210421) * bСССС04210421) % b04210421СС04210421 != b0421ССС04210421) {
            bСССС04210421 = 84;
            b0421ССС04210421 = b0421С0421С04210421();
        }
        return new String(Hex.encodeHex(bytes));
    } catch (Exception e) {
        return "null";
    }
}
项目:okhttp-awssigner    文件:Tools.java   
static Mac getAlgorithmSilent(String algorithm, byte[] key) {
    try {
        Mac mac = Mac.getInstance(algorithm);
        mac.init(new SecretKeySpec(key, algorithm));
        return mac;
    } catch (InvalidKeyException | NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}
项目:Cable-Android    文件:EncryptingPartOutputStream.java   
private Cipher initializeCipher(Mac mac, SecretKeySpec key) throws IOException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException {
  Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
  cipher.init(Cipher.ENCRYPT_MODE, key);

  byte[] ivBytes = cipher.getIV();
  mac.update(ivBytes);
  super.write(ivBytes, 0, ivBytes.length);

  return cipher;
}
项目:pac4j-async    文件:FacebookProfileUrlCalculator.java   
/**
 * The code in this method is based on this blog post: https://www.sammyk.me/the-single-most-important-way-to-make-your-facebook-app-more-secure
 * and this answer: https://stackoverflow.com/questions/7124735/hmac-sha256-algorithm-for-signature-calculation
 *
 * @param url the URL to which we're adding the proof
 * @param token the application token we pass back and forth
 * @param configuration the current configuration
 * @return URL with the appsecret_proof parameter added
 */
public String computeAppSecretProof(final String url, final OAuth2AccessToken token, final OAuth20Configuration configuration) {
    try {
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(configuration.getSecret().getBytes("UTF-8"), "HmacSHA256");
        sha256_HMAC.init(secret_key);
        String proof = org.apache.commons.codec.binary.Hex.encodeHexString(sha256_HMAC.doFinal(token.getAccessToken().getBytes("UTF-8")));
        final String computedUrl = CommonHelper.addParameter(url, APPSECRET_PARAMETER, proof);
        return computedUrl;
    } catch (final Exception e) {
        throw new TechnicalException("Unable to compute appsecret_proof", e);
    }
}
项目:openjdk-jdk10    文件: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");
    }
}
项目:jdk8u-jdk    文件:IntegrityHmac.java   
/**
 * 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);
    }
}
项目:ipack    文件:JceKeyTransAuthenticatedRecipient.java   
public RecipientOperator getRecipientOperator(AlgorithmIdentifier keyEncryptionAlgorithm, final AlgorithmIdentifier contentMacAlgorithm, byte[] encryptedContentEncryptionKey)
    throws CMSException
{
    final Key secretKey = extractSecretKey(keyEncryptionAlgorithm, contentMacAlgorithm, encryptedContentEncryptionKey);

    final Mac dataMac = contentHelper.createContentMac(secretKey, contentMacAlgorithm);

    return new RecipientOperator(new MacCalculator()
    {
        public AlgorithmIdentifier getAlgorithmIdentifier()
        {
            return contentMacAlgorithm;
        }

        public GenericKey getKey()
        {
            return new GenericKey(secretKey);
        }

        public OutputStream getOutputStream()
        {
            return new MacOutputStream(dataMac);
        }

        public byte[] getMac()
        {
            return dataMac.doFinal();
        }
    });
}
项目:boohee_v5.6    文件:CryptoUtil.java   
public static byte[] digestWithHmacSha1(byte[] bArr, byte[] bArr2) {
    Mac instance;
    try {
        instance = Mac.getInstance("HmacSHA1");
    } catch (NoSuchAlgorithmException e) {
        instance = Mac.getInstance(HMAC_SHA_1);
    }
    instance.init(new SecretKeySpec(bArr2, RAW));
    return instance.doFinal(bArr);
}
项目:PeSanKita-android    文件:MasterCipher.java   
public MasterCipher(MasterSecret masterSecret) {
  try {
    this.masterSecret = masterSecret;       
    this.encryptingCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    this.decryptingCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    this.hmac             = Mac.getInstance("HmacSHA1");
  } catch (NoSuchPaddingException | NoSuchAlgorithmException nspe) {
    throw new AssertionError(nspe);
  }
}
项目:Cable-Android    文件:MasterCipher.java   
public byte[] decryptBytes(@NonNull byte[] decodedBody) throws InvalidMessageException {
  try {
    Mac mac              = getMac(masterSecret.getMacKey());
    byte[] encryptedBody = verifyMacBody(mac, decodedBody);

    Cipher cipher        = getDecryptingCipher(masterSecret.getEncryptionKey(), encryptedBody);
    byte[] encrypted     = getDecryptedBody(cipher, encryptedBody);

    return encrypted;
  } catch (GeneralSecurityException ge) {
    throw new InvalidMessageException(ge);
  }
}
项目:PeSanKita-android    文件:MasterCipher.java   
public byte[] getMacFor(String content) {
  Log.w("MasterCipher", "Macing: " + content);
  try {
    Mac mac = getMac(masterSecret.getMacKey());
    return mac.doFinal(content.getBytes());
  } catch (GeneralSecurityException ike) {
    throw new AssertionError(ike);
  }
}
项目:jdk8u-jdk    文件:MacSameTest.java   
@Override
public void doTest(String algo) throws NoSuchAlgorithmException,
        NoSuchProviderException, InvalidKeyException {
    Mac mac;
    try {
        mac = Mac.getInstance(algo, "SunJCE");
    } catch (NoSuchAlgorithmException nsae) {
        // depending on Solaris configuration,
        // it can support HMAC or not with Mac
        System.out.println("Expected NoSuchAlgorithmException thrown: "
                + nsae);
        return;
    }

    byte[] plain = new byte[MESSAGE_SIZE];
    for (int i = 0; i < MESSAGE_SIZE; i++) {
        plain[i] = (byte) (i % 256);
    }

    byte[] tail = new byte[plain.length - OFFSET];
    System.arraycopy(plain, OFFSET, tail, 0, tail.length);

    SecureRandom srdm = new SecureRandom();
    byte[] keyVal = new byte[KEY_SIZE];
    srdm.nextBytes(keyVal);
    SecretKeySpec keySpec = new SecretKeySpec(keyVal, "HMAC");

    mac.init(keySpec);
    byte[] result1 = mac.doFinal(plain);

    mac.reset();
    mac.update(plain[0]);
    mac.update(plain, 1, OFFSET - 1);
    byte[] result2 = mac.doFinal(tail);

    if (!java.util.Arrays.equals(result1, result2)) {
        throw new RuntimeException("result1 and result2 are not the same");
    }
}
项目:bird-java    文件: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);
}