HmacSHA1加密

@param data 明文字符串
@param key  秘钥
@return 16进制密文
778696
public static String hmacSHA1(String data, String key) {
        return hmacSHA1(data.getBytes(), key.getBytes());
    }
815742
protected function calculate_RFC2104HMAC($data, $key) {
			return base64_encode (
				pack("H*", sha1((str_pad($key, 64, chr(0x00))
				^(str_repeat(chr(0x5c), 64))) .
				pack("H*", sha1((str_pad($key, 64, chr(0x00))
				^(str_repeat(chr(0x36), 64))) . $data))))
			);
		}
512920
protected function decrypt($data, $key)
    {
        $hmac       = mb_substr($data, 0, 32, '8bit');
        $iv         = mb_substr($data, 32, 16, '8bit');
        $ciphertext = mb_substr($data, 48, null, '8bit');
        // Authentication
        $hmacNew = hash_hmac(
            'SHA256',
            $iv . $ciphertext,
            mb_substr($key, 32, null, '8bit'),
            true
        );
        if (! hash_equals($hmac, $hmacNew)) {
            throw new Exception\AuthenticationFailedException('Authentication failed');
        }
        // Decrypt
        return openssl_decrypt(
            $ciphertext,
            'AES-256-CBC',
            mb_substr($key, 0, 32, '8bit'),
            OPENSSL_RAW_DATA,
            $iv
        );
    }
231597
func HmacSHA1(key, origData []byte) (sum []byte) {
	mac := hmac.New(sha1.New, key)
	mac.Write(origData)
	return mac.Sum(nil)
}
267011
public String calculateRFC2104HMAC(String data, String key)
        throws java.security.SignatureException {
        
        String result;
        try {
            // get an hmac_sha1 key from the raw key bytes
            SecretKeySpec signingKey = 
                new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);

            // get an hmac_sha1 Mac instance and initialize with the signing key
            Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
            mac.init(signingKey);
            
            // compute the hmac on input data bytes
            byte[] rawHmac = mac.doFinal(data.getBytes());
            
            // base64-encode the hmac
            result = new String(Base64.encodeBase64(rawHmac));
        } 
        catch (Exception e) {
            throw new SignatureException("Failed to generate HMAC", e);
        }
        
        return result;
    }
1095604
public static byte[] hmacSha1(final byte[] input, final byte[] key)
		throws GeneralSecurityException {
		try {
			SecretKey secretKey = new SecretKeySpec(key, HMACSHA1_NAME);
			Mac mac = Mac.getInstance(HMACSHA1_NAME);
			mac.init(secretKey);
			return mac.doFinal(input);
		} catch (NoSuchAlgorithmException e) {
			throw new ImpossibleException(e);
		}
	}
507277
public static String decrypt(String data, byte[] key)
    {
        try
        {
            Key k = toSecretKey(key);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, k);
            byte[] toByteArray = Hex.decodeHex(data.toCharArray());
            byte[] decrypted = cipher.doFinal(toByteArray);
            return new String(decrypted, "UTF-8");
        }
        catch (GeneralSecurityException e)
        {
            throw new RuntimeException("Failed to decrypt.", e);
        }
        catch (UnsupportedEncodingException e)
        {
            throw new RuntimeException(e);
        }
        catch (DecoderException e)
        {
            throw new RuntimeException(e);
        }
    }
85811
public static byte[] encryptAES2Base64(byte[] data, byte[] key) {
        try {
            return Base64.getEncoder().encode(encryptAES(data, key));
        } catch (Exception e) {
            return null;
        }
    }
951069
private static byte[] sha256(byte[] data) {
		MessageDigest md = null;
		try {
			md = MessageDigest.getInstance(ALGORITHM_SHA256);
			md.reset();
			md.update(data);
			return md.digest();
		} catch (Exception e) {
			LogUtil.writeErrorLog("SHA256计算失败", e);
			return null;
		}
	}
410208
def core_hmac_sha1(key, data)
      bkey = str2binb(key)
      bkey = core_sha1(bkey, key.length * $chrsz) if bkey.length > 16

      ipad = Array.new(16, 0)
      opad = Array.new(16, 0)
      # for(var i = 0; i < 16; i++)
      i = 0
      while i < 16
        ipad[i] = (bkey[i] || 0) ^ 0x36363636
        opad[i] = (bkey[i] || 0) ^ 0x5C5C5C5C
        i += 1
      end

      hash = core_sha1((ipad + str2binb(data)), 512 + data.length * $chrsz)
      core_sha1((opad + hash), 512 + 160)
    end
1243555
function(key, seqNum, record) {
  /* MAC is computed like so:
  HMAC_hash(
    key, seqNum +
      TLSCompressed.type +
      TLSCompressed.version +
      TLSCompressed.length +
      TLSCompressed.fragment)
  */
  var hmac = forge.hmac.create();
  hmac.start('SHA1', key);
  var b = forge.util.createBuffer();
  b.putInt32(seqNum[0]);
  b.putInt32(seqNum[1]);
  b.putByte(record.type);
  b.putByte(record.version.major);
  b.putByte(record.version.minor);
  b.putInt16(record.length);
  b.putBytes(record.fragment.bytes());
  hmac.update(b.getBytes());
  return hmac.digest().getBytes();
}
846583
protected static final byte[] signISO9796(byte[][] key, byte[] data, int off, int len) throws Exception {
        CachingKey ck = new CachingKey(key, data, off, len);
        CachingKey result = cryptoKeysMap.get(ck);

        if (result != null) {
            result.successfulUses += 1;
            result.reused = true;
            return result.result;
        } else {
            if (cryptoKeysMap.size() > MAX_CACHE) {
                try {
                    CachingKey[] keys = cryptoKeysMap.keySet().toArray(new CachingKey[cryptoKeysMap.size()]);
                    Arrays.sort(keys, cachingKeyComparator);
                    if (cachingKeyComparator.compare(keys[0], keys[keys.length - 1]) < 0) {
                        for (int i = 0; i < cryptoKeysMap.size() / 5; i++) {
                            cryptoKeysMap.remove(keys[i]);
                            keys[i + 1 * cryptoKeysMap.size() / 5].successfulUses--;
                            keys[i + 2 * cryptoKeysMap.size() / 5].successfulUses--;
                            keys[i + 3 * cryptoKeysMap.size() / 5].successfulUses--;
                            keys[i + 4 * cryptoKeysMap.size() / 5].successfulUses--;
                        }
                    } else {
                        for (int i = 0; i < cryptoKeysMap.size() / 5; i++) {
                            cryptoKeysMap.remove(keys[keys.length - 1 - i]);
                            keys[keys.length - 1 - i - 1 * cryptoKeysMap.size() / 5].successfulUses--;
                            keys[keys.length - 1 - i - 2 * cryptoKeysMap.size() / 5].successfulUses--;
                            keys[keys.length - 1 - i - 3 * cryptoKeysMap.size() / 5].successfulUses--;
                            keys[keys.length - 1 - i - 4 * cryptoKeysMap.size() / 5].successfulUses--;
                        }
                    }
                } catch (Exception e) {
                    // do nothing. since this code is used for the command line utility, no log is taken.
                }
                 
            }
        }

        /** Invoked by LTPADigSignature **/
        BigInteger n = new BigInteger(key[0]);
        BigInteger e = new BigInteger(key[2]);
        BigInteger p = new BigInteger(key[3]);
        BigInteger q = new BigInteger(key[4]);
        BigInteger d = e.modInverse((p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE)));
        KeyFactory kFact = null;
        if (LTPAKeyUtil.isIBMJCEAvailable()) {
            kFact = KeyFactory.getInstance(CRYPTO_ALGORITHM, IBMJCE_NAME);
        } else {
            kFact = KeyFactory.getInstance(CRYPTO_ALGORITHM);
        }


        BigInteger pep = new BigInteger(key[5]);
        BigInteger peq = new BigInteger(key[6]);
        BigInteger crtC = new BigInteger(key[7]);
        RSAPrivateCrtKeySpec privCrtKeySpec = new RSAPrivateCrtKeySpec(n, e, d, p, q, pep, peq, crtC);
        PrivateKey privKey = kFact.generatePrivate(privCrtKeySpec);

        Signature rsaSig = null;
        if (LTPAKeyUtil.isIBMJCEAvailable()) {
            rsaSig = Signature.getInstance(SIGNATURE_ALGORITHM, IBMJCE_NAME);
        } else {
            rsaSig = Signature.getInstance(SIGNATURE_ALGORITHM);
        }
        rsaSig.initSign(privKey);
        rsaSig.update(data, off, len);
        byte[] sig = rsaSig.sign();

        cryptoKeysMap.put(ck, ck);
        ck.result = sig;
        ck.successfulUses = 0;

        return sig;
    }
1179839
@Override
	public HMAC createHMACSHA1(byte[] hmacKey) throws CryptoException {
		try {
			return new BCHmacAdapter(hmacKey, "SHA1");
		} catch (Exception e) {
			AndroidPlatform.getInstance().getLogger().logException(e.getMessage());
			return null;
		}
	}
805780
protected function hmac($key = '', $data = '')
    {
        if ($data == '') {
            $this->errorMessage[] = 'DATA FOR HMAC: MISSING!';
            return false;
        }
        if ($key == '') {
            $this->errorMessage[] = 'KEY FOR HMAC: MISSING!';
            return false;
        }
        return hash_hmac('md5', $data, trim($key));
    }
123081
protected function encrypt($data, $key)
    {
        $iv = random_bytes(16); // AES block size in CBC mode
        // Encryption
        $ciphertext = openssl_encrypt(
            $data,
            'AES-256-CBC',
            mb_substr($key, 0, 32, '8bit'),
            OPENSSL_RAW_DATA,
            $iv
        );
        // Authentication
        $hmac = hash_hmac(
            'SHA256',
            $iv . $ciphertext,
            mb_substr($key, 32, null, '8bit'),
            true
        );
        return $hmac . $iv . $ciphertext;
    }
356765
private static byte[] sha1(byte[] data) {
		MessageDigest md = null;
		try {
			md = MessageDigest.getInstance(ALGORITHM_SHA1);
			md.reset();
			md.update(data);
			return md.digest();
		} catch (Exception e) {
			LogUtil.writeErrorLog("SHA1计算失败", e);
			return null;
		}
	}
1103889
public static byte[] sha1(byte[] data) {
        try {
            //Attempt to get a MessageDigest that uses SHA1
            MessageDigest md = MessageDigest.getInstance("SHA1");
            //Hash the data
            return md.digest(data);
        } catch (NoSuchAlgorithmException e) {
            //Alright, you might have an old system.
            throw new InternalError("SHA-1 is not supported on this platform - Outdated?");
        }
    }