Java Code Examples for javax.crypto.Mac

The following are top voted examples for showing how to use javax.crypto.Mac. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: qcloudClient   File: Sign.java   View source code 8 votes vote down vote up
/**
 * @brief 签名
 * @author [email protected]
 * @date 2014-08-13 21:07:27
 *
 * @param signStr 被加密串
 * @param secret 加密密钥
 *
 * @return
 */
public static String sign(String signStr, String secret) 
		throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException 
{

    String sig = null;
    Mac mac = Mac.getInstance(HMAC_ALGORITHM);
    SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes(CONTENT_CHARSET), mac.getAlgorithm());

    mac.init(secretKey);
    byte[] hash = mac.doFinal(signStr.getBytes(CONTENT_CHARSET));

    // base64
    //sig = new String(new BASE64Encoder().encode(hash).getBytes());
    //sig = new String(Base64.encodeBase64(hash));
    sig = new String(Base64.encode(hash));

    return sig;
}
 
Example 2
Project: jdk8u-jdk   File: MacKAT.java   View source code 7 votes vote down vote up
@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);
}
 
Example 3
Project: libcwfincore   File: GdaxExchangeSession.java   View source code 7 votes vote down vote up
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()));
}
 
Example 4
Project: gplaymusic   File: Signable.java   View source code 6 votes vote down vote up
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);
  }
}
 
Example 5
Project: OpenJSharp   File: AesDkCrypto.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 6
Project: wolfcrypt-jni   File: WolfCryptMacTest.java   View source code 6 votes vote down vote up
@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) { }
}
 
Example 7
Project: openjdk-jdk10   File: PBMacBuffer.java   View source code 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 8
Project: OpenJSharp   File: DOMHMACSignatureMethod.java   View source code 6 votes vote down vote up
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();
}
 
Example 9
Project: QiNiuTest   File: Auth.java   View source code 6 votes vote down vote up
/**
 * 生成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;
}
 
Example 10
Project: FirefoxData-android   File: HKDF.java   View source code 6 votes vote down vote up
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;
}
 
Example 11
Project: Android_Code_Arbiter   File: GoogleMapsSigUtil.java   View source code 6 votes vote down vote up
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;
}
 
Example 12
Project: lams   File: HMAC_SHA1.java   View source code 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 13
Project: EasyAndroid   File: EncryptTool.java   View source code 6 votes vote down vote up
/**
 * 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;
    }
}
 
Example 14
Project: Equella   File: D2LSigner.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 15
Project: openjdk-jdk10   File: PBMacBuffer.java   View source code 5 votes vote down vote up
/**
 * 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;
}
 
Example 16
Project: bittrex4j   File: EncryptionUtility.java   View source code 5 votes vote down vote up
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);
}
 
Example 17
Project: BaseCore   File: EncryptUtils.java   View source code 5 votes vote down vote up
/**
 * 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;
    }
}
 
Example 18
Project: mumu   File: HmacCoder.java   View source code 5 votes vote down vote up
/**
 * 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);
}
 
Example 19
Project: JwtDemo   File: JwtApp.java   View source code 5 votes vote down vote up
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;
}
 
Example 20
Project: mumu-core   File: HmacCoder.java   View source code 5 votes vote down vote up
/**
 * 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);
}
 
Example 21
Project: googles-monorepo-demo   File: MacHashFunctionTest.java   View source code 5 votes vote down vote up
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());
}
 
Example 22
Project: tumbviewer   File: OAuth1SigningHelper.java   View source code 5 votes vote down vote up
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 "";
    }
}
 
Example 23
Project: aws-sdk-java-v2   File: AbstractAwsSigner.java   View source code 5 votes vote down vote up
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);
    }
}
 
Example 24
Project: OpenJSharp   File: IntegrityHmac.java   View source code 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 25
Project: mumu   File: HmacCoder.java   View source code 5 votes vote down vote up
/**
 * 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);
}
 
Example 26
Project: googles-monorepo-demo   File: MacHashFunction.java   View source code 5 votes vote down vote up
private static boolean supportsClone(Mac mac) {
  try {
    mac.clone();
    return true;
  } catch (CloneNotSupportedException e) {
    return false;
  }
}
 
Example 27
Project: JAVA-   File: HmacCoder.java   View source code 5 votes vote down vote up
/**
 * 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);
}
 
Example 28
Project: letv   File: rcrrrr.java   View source code 5 votes vote down vote up
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";
    }
}
 
Example 29
Project: okhttp-awssigner   File: Tools.java   View source code 5 votes vote down vote up
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);
    }
}
 
Example 30
Project: Cable-Android   File: EncryptingPartOutputStream.java   View source code 5 votes vote down vote up
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;
}
 
Example 31
Project: pac4j-async   File: FacebookProfileUrlCalculator.java   View source code 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 32
Project: openjdk-jdk10   File: LargeByteBufferTest.java   View source code 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 33
Project: jdk8u-jdk   File: IntegrityHmac.java   View source code 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 34
Project: ipack   File: JceKeyTransAuthenticatedRecipient.java   View source code 5 votes vote down vote up
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();
        }
    });
}
 
Example 35
Project: boohee_v5.6   File: CryptoUtil.java   View source code 5 votes vote down vote up
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);
}
 
Example 36
Project: PeSanKita-android   File: MasterCipher.java   View source code 5 votes vote down vote up
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);
  }
}
 
Example 37
Project: Cable-Android   File: MasterCipher.java   View source code 5 votes vote down vote up
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);
  }
}
 
Example 38
Project: PeSanKita-android   File: MasterCipher.java   View source code 5 votes vote down vote up
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);
  }
}
 
Example 39
Project: jdk8u-jdk   File: MacSameTest.java   View source code 5 votes vote down vote up
@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");
    }
}
 
Example 40
Project: bird-java   File: HmacCoder.java   View source code 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);
}