All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.cryptomator.cryptolib.common.MacSupplier Maven / Gradle / Ivy

Go to download

This library contains all cryptographic functions that are used by Cryptomator.

There is a newer version: 2.2.0
Show newest version
/*******************************************************************************
 * Copyright (c) 2016 Sebastian Stenzel and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the accompanying LICENSE.txt.
 *
 * Contributors:
 *     Sebastian Stenzel - initial API and implementation
 *******************************************************************************/
package org.cryptomator.cryptolib.common;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;
import javax.crypto.SecretKey;

public final class MacSupplier {

	public static final MacSupplier HMAC_SHA256 = new MacSupplier("HmacSHA256");

	private final String macAlgorithm;
	private final ThreadLocal threadLocal;

	public MacSupplier(String macAlgorithm) {
		this.macAlgorithm = macAlgorithm;
		this.threadLocal = new Provider();
	}

	private class Provider extends ThreadLocal {
		@Override
		protected Mac initialValue() {
			try {
				return Mac.getInstance(macAlgorithm);
			} catch (NoSuchAlgorithmException e) {
				throw new IllegalArgumentException("Invalid MAC algorithm.", e);
			}
		}
	}

	public Mac withKey(SecretKey key) {
		try {
			final Mac mac = threadLocal.get();
			mac.init(key);
			return mac;
		} catch (InvalidKeyException e) {
			throw new IllegalArgumentException("Invalid key.", e);
		}
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy