javax.crypto.Mac Java Examples
The following examples show how to use
javax.crypto.Mac.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: EmptyByteBufferTest.java From jdk8u-jdk with GNU General Public License v2.0 | 6 votes |
@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[0]; ByteBuffer buf = ByteBuffer.wrap(data); mac.update(buf); mac.doFinal(); }
Example #2
Source File: CcSigned.java From takes with MIT License | 6 votes |
@Override public Identity decode(final byte[] bytes) throws IOException { final Mac mac = this.mac(); if (bytes.length < mac.getMacLength()) { throw new IOException("Invalid data size"); } final byte[] signature = new byte[mac.getMacLength()]; final byte[] encoded = new byte[bytes.length - signature.length]; System.arraycopy(bytes, 0, encoded, 0, encoded.length); System.arraycopy( bytes, encoded.length, signature, 0, signature.length ); final byte[] actual = mac.doFinal(encoded); if (!Arrays.equals(actual, signature)) { throw new IOException("Bad signature"); } return this.cdc.decode(encoded); }
Example #3
Source File: PBMacBuffer.java From dragonwell8_jdk with GNU General Public License v2.0 | 6 votes |
/** * NULL ByteBuffer test case. Pass NULL ByteBuffer to Mac.update(ByteBuffer * buffer) method. An IllegalArgumentException expected. * * @param theMac Mac object to test. * @return true - test case pass; false - otherwise. */ protected boolean nullByteBufferTest(Mac theMac) { try { ByteBuffer buf = null; theMac.update(buf); theMac.doFinal(); } catch (IllegalArgumentException e) { // expected exception has been thrown return true; } System.out.println("FAIL: " + "IllegalArgumentException hasn't been thrown as expected"); return false; }
Example #4
Source File: VotifierProtocol2DecoderTest.java From NuVotifier with GNU General Public License v3.0 | 6 votes |
private void sendVote(Vote vote, Key key, boolean expectSuccess) throws Exception { // Create a well-formed request EmbeddedChannel channel = createChannel(); JSONObject object = new JSONObject(); JsonObject payload = vote.serialize(); payload.addProperty("challenge", SESSION.getChallenge()); String payloadEncoded = GsonInst.gson.toJson(payload); object.put("payload", payloadEncoded); Mac mac = Mac.getInstance("HmacSHA256"); mac.init(key); object.put("signature", Base64.getEncoder().encodeToString(mac.doFinal(payloadEncoded.getBytes(StandardCharsets.UTF_8)))); if (expectSuccess) { assertTrue(channel.writeInbound(object.toString())); assertEquals(vote, channel.readInbound()); assertFalse(channel.finish()); } else { try { channel.writeInbound(object.toString()); } finally { channel.close(); } } }
Example #5
Source File: PBMacBuffer.java From jdk8u_jdk with GNU General Public License v2.0 | 6 votes |
/** * NULL ByteBuffer test case. Pass NULL ByteBuffer to Mac.update(ByteBuffer * buffer) method. An IllegalArgumentException expected. * * @param theMac Mac object to test. * @return true - test case pass; false - otherwise. */ protected boolean nullByteBufferTest(Mac theMac) { try { ByteBuffer buf = null; theMac.update(buf); theMac.doFinal(); } catch (IllegalArgumentException e) { // expected exception has been thrown return true; } System.out.println("FAIL: " + "IllegalArgumentException hasn't been thrown as expected"); return false; }
Example #6
Source File: IntegrityHmac.java From hottub with GNU General Public License v2.0 | 6 votes |
/** * Method IntegrityHmac * * @throws XMLSignatureException */ public IntegrityHmac() throws XMLSignatureException { String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI()); if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Created IntegrityHmacSHA1 using " + algorithmID); } try { this.macAlgorithm = Mac.getInstance(algorithmID); } catch (java.security.NoSuchAlgorithmException ex) { Object[] exArgs = { algorithmID, ex.getLocalizedMessage() }; throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); } }
Example #7
Source File: MacSyslogMessageModifier.java From syslog4j with GNU Lesser General Public License v2.1 | 6 votes |
public MacSyslogMessageModifier(MacSyslogMessageModifierConfig config) throws SyslogRuntimeException { super(config); this.config = config; try { this.mac = Mac.getInstance(config.getMacAlgorithm()); this.mac.init(config.getKey()); } catch (NoSuchAlgorithmException nsae) { throw new SyslogRuntimeException(nsae); } catch (InvalidKeyException ike) { throw new SyslogRuntimeException(ike); } }
Example #8
Source File: NullByteBufferTest.java From jdk8u_jdk with GNU General Public License v2.0 | 6 votes |
@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); try { ByteBuffer buf = null; mac.update(buf); mac.doFinal(); throw new RuntimeException( "Expected IllegalArgumentException not thrown"); } catch (IllegalArgumentException e) { System.out.println("Expected IllegalArgumentException thrown: " + e); } }
Example #9
Source File: EIDUtils.java From beacons-android with Apache License 2.0 | 6 votes |
public static byte[] computeIdentityKey(byte[] sharedSecret, byte[] serverPublicKey, byte[] beaconPublicKey) throws InvalidKeyException, NoSuchAlgorithmException { if (Util.isZeroBuffer(sharedSecret)) { throw new InvalidKeyException("Shared secret is zero"); } byte[] salt = new byte[serverPublicKey.length + beaconPublicKey.length]; System.arraycopy(serverPublicKey, 0, salt, 0, serverPublicKey.length); System.arraycopy(beaconPublicKey, 0, salt, serverPublicKey.length, beaconPublicKey.length); Mac mac = Mac.getInstance("hmacSHA256"); // hkdf extract mac.init(new SecretKeySpec(salt, "hmacSHA256")); byte[] pseudoRandomKey = mac.doFinal(sharedSecret); // hkdf expand mac.reset(); mac.init(new SecretKeySpec(pseudoRandomKey, "hmacSHA256")); return mac.doFinal(new byte[]{1}); }
Example #10
Source File: AesDkCrypto.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
/** * 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 #11
Source File: CrypterProxy.java From Android-Goldfinger with Apache License 2.0 | 6 votes |
@Nullable public String encrypt(@NonNull BiometricPrompt.CryptoObject cryptoObject, @NonNull String value) { Cipher cipher = cryptoObject.getCipher(); if (cipher != null && cipherCrypter != null) { return cipherCrypter.encrypt(cipher, value); } Mac mac = cryptoObject.getMac(); if (mac != null && macCrypter != null) { return macCrypter.encrypt(mac, value); } Signature signature = cryptoObject.getSignature(); if (signature != null && signatureCrypter != null) { return signatureCrypter.encrypt(signature, value); } return null; }
Example #12
Source File: OAuthUtil.java From carbon-identity with Apache License 2.0 | 6 votes |
/** * Generates a random number using two UUIDs and HMAC-SHA1 * * @return generated secure random number * @throws IdentityOAuthAdminException Invalid Algorithm or Invalid Key */ public static String getRandomNumber() throws IdentityOAuthAdminException { try { String secretKey = UUIDGenerator.generateUUID(); String baseString = UUIDGenerator.generateUUID(); SecretKeySpec key = new SecretKeySpec(secretKey.getBytes(Charsets.UTF_8), ALGORITHM); Mac mac = Mac.getInstance(ALGORITHM); mac.init(key); byte[] rawHmac = mac.doFinal(baseString.getBytes(Charsets.UTF_8)); String random = Base64.encode(rawHmac); // Registry doesn't have support for these character. random = random.replace("/", "_"); random = random.replace("=", "a"); random = random.replace("+", "f"); return random; } catch (Exception e) { throw new IdentityOAuthAdminException("Error when generating a random number.", e); } }
Example #13
Source File: GoogleAuthCode.java From zheshiyigeniubidexiangmu with MIT License | 6 votes |
private static int verify_code(byte[] key, long t) throws NoSuchAlgorithmException, InvalidKeyException { byte[] data = new byte[8]; long value = t; for (int i = 8; i-- > 0; value >>>= 8) { data[i] = (byte) value; } SecretKeySpec signKey = new SecretKeySpec(key, "HmacSHA1"); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(signKey); byte[] hash = mac.doFinal(data); int offset = hash[20 - 1] & 0xF; // We're using a long because Java hasn't got unsigned int. long truncatedHash = 0; for (int i = 0; i < 4; ++i) { truncatedHash <<= 8; // We are dealing with signed bytes: // we just keep the first byte. truncatedHash |= (hash[offset + i] & 0xFF); } truncatedHash &= 0x7FFFFFFF; truncatedHash %= 1000000; return (int) truncatedHash; }
Example #14
Source File: MasterCipher.java From Silence with GNU General Public License v3.0 | 6 votes |
private byte[] verifyMacBody(@NonNull Mac hmac, @NonNull byte[] encryptedAndMac) throws InvalidMessageException { if (encryptedAndMac.length < hmac.getMacLength()) { throw new InvalidMessageException("length(encrypted body + MAC) < length(MAC)"); } byte[] encrypted = new byte[encryptedAndMac.length - hmac.getMacLength()]; System.arraycopy(encryptedAndMac, 0, encrypted, 0, encrypted.length); byte[] remoteMac = new byte[hmac.getMacLength()]; System.arraycopy(encryptedAndMac, encryptedAndMac.length - remoteMac.length, remoteMac, 0, remoteMac.length); byte[] localMac = hmac.doFinal(encrypted); if (!Arrays.equals(remoteMac, localMac)) throw new InvalidMessageException("MAC doesen't match."); return encrypted; }
Example #15
Source File: HiddenDerivationService.java From guardedbox with GNU Affero General Public License v3.0 | 6 votes |
/** * Derives an array of bytes from a source and a secret key. * * @param source The source. * @param length The length of the derived array of bytes. * @return The derived array of bytes. */ public byte[] derive( String source, int length) { byte[] key = derivationKeys.get(length); if (key == null) { throw new ServiceException(String.format("No key of length %s was defined", length)); } try { String algorithm = "HmacSHA" + length * 8; Mac mac = Mac.getInstance(algorithm); SecretKeySpec keySpec = new SecretKeySpec(key, algorithm); mac.init(keySpec); return mac.doFinal(source.getBytes(StandardCharsets.UTF_8)); } catch (NoSuchAlgorithmException | InvalidKeyException e) { throw new ServiceException("Error during the derivation process", e); } }
Example #16
Source File: HmacJwsSignatureVerifier.java From cxf with Apache License 2.0 | 5 votes |
@Override public JwsVerificationSignature createJwsVerificationSignature(JwsHeaders headers) { final String sigAlgo = checkAlgorithm(headers.getSignatureAlgorithm()); Mac mac = HmacUtils.getInitializedMac(key, AlgorithmUtils.toJavaName(sigAlgo), hmacSpec); return new HmacJwsVerificationSignature(mac); }
Example #17
Source File: SignUtil.java From gameserver with Apache License 2.0 | 5 votes |
private static byte[] hmacSha1(byte[] secret, byte[] data) throws NoSuchAlgorithmException, InvalidKeyException { String algo = "HmacSHA1"; SecretKey secretKey = new SecretKeySpec(secret, algo); Mac m = Mac.getInstance(algo); m.init(secretKey); return m.doFinal(data); }
Example #18
Source File: Utils.java From NetStorageKit-Java with Apache License 2.0 | 5 votes |
/** * Computes the HMAC hash of a given byte[]. This is a wrapper over the Mac crypto functions. * * @param data byte[] of content to hash * @param key secret key to salt the hash * @param hashType determines which alogirthm to use. The recommendation is to use HMAC-SHA256 * @return a byte[] presenting the HMAC hash of the source data. */ public static byte[] computeKeyedHash(byte[] data, String key, KeyedHashAlgorithm hashType) { if (data == null || key == null) return null; try { Mac mac = Mac.getInstance(hashType.getAlgorithm()); mac.init(new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), hashType.getAlgorithm())); return mac.doFinal(data); } catch (NoSuchAlgorithmException | InvalidKeyException e) { throw new IllegalArgumentException("This should never happen!", e); } }
Example #19
Source File: TOTPHelper.java From passman-android with GNU General Public License v3.0 | 5 votes |
public static int generate(byte[] key, long t, int digits) { int r = 0; try { t /= 30; byte[] data = new byte[8]; long value = t; for (int i = 8; i-- > 0; value >>>= 8) { data[i] = (byte) value; } SecretKeySpec signKey = new SecretKeySpec(key, SHA1); Mac mac = Mac.getInstance(SHA1); mac.init(signKey); byte[] hash = mac.doFinal(data); int offset = hash[20 - 1] & 0xF; long truncatedHash = 0; for (int i = 0; i < 4; ++i) { truncatedHash <<= 8; truncatedHash |= (hash[offset + i] & 0xFF); } truncatedHash &= 0x7FFFFFFF; truncatedHash %= Math.pow(10,digits); r = (int) truncatedHash; } catch(Exception e){ } return r; }
Example #20
Source File: Hmac.java From cstc with GNU General Public License v3.0 | 5 votes |
@Override protected byte[] perform(byte[] input) throws Exception { byte[] key = this.keyTxt.getText().getBytes(); String algo = "Hmac" + (String) hashAlgoBox.getSelectedItem(); SecretKeySpec signingKey = new SecretKeySpec(key, algo); Mac mac = Mac.getInstance(algo); mac.init(signingKey); return Hex.encode(mac.doFinal(input)); }
Example #21
Source File: PKCS12KeyStore.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
private byte[] calculateMac(char[] passwd, byte[] data) throws IOException { byte[] mData = null; String algName = "SHA1"; try { // Generate a random salt. byte[] salt = getSalt(); // generate MAC (MAC key is generated within JCE) Mac m = Mac.getInstance("HmacPBESHA1"); PBEParameterSpec params = new PBEParameterSpec(salt, MAC_ITERATION_COUNT); SecretKey key = getPBEKey(passwd); m.init(key, params); m.update(data); byte[] macResult = m.doFinal(); // encode as MacData MacData macData = new MacData(algName, macResult, salt, MAC_ITERATION_COUNT); DerOutputStream bytes = new DerOutputStream(); bytes.write(macData.getEncoded()); mData = bytes.toByteArray(); } catch (Exception e) { throw new IOException("calculateMac failed: " + e, e); } return mData; }
Example #22
Source File: HmacEncryptor.java From beihu-boot with Apache License 2.0 | 5 votes |
/** * hash加密模板 * * @param data 数据 * @param algorithm 加密算法 * @return 密文字节数组 */ public static byte[] encrypt(byte[] data, byte[] key, String algorithm) throws NoSuchAlgorithmException, InvalidKeyException { if (data == null || data.length == 0 || key == null || key.length == 0) return null; SecretKeySpec secretKey = new SecretKeySpec(key, algorithm); Mac mac = Mac.getInstance(algorithm); mac.init(secretKey); return mac.doFinal(data); }
Example #23
Source File: EncryptUtils.java From DevUtils with Apache License 2.0 | 5 votes |
/** * Hmac 加密模版方法 * @param data 待加密数据 * @param key 密钥 * @param algorithm 算法 * @return 指定加密算法和密钥, 加密后的数据 */ public static byte[] hmacTemplate(final byte[] data, final byte[] key, final 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 (Exception e) { JCLogUtils.eTag(TAG, e, "hmacTemplate"); return null; } }
Example #24
Source File: DecryptingPartInputStream.java From bcm-android with GNU General Public License v3.0 | 5 votes |
private static Mac initializeMac(SecretKeySpec key) { try { Mac hmac = Mac.getInstance("HmacSHA1"); hmac.init(key); return hmac; } catch (NoSuchAlgorithmException | InvalidKeyException e) { throw new AssertionError(e); } }
Example #25
Source File: TOTP.java From zheshiyigeniubidexiangmu with MIT License | 5 votes |
/** * 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); } }
Example #26
Source File: Des3DkCrypto.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
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); }
Example #27
Source File: RegionsApiUtil.java From cloudstack with Apache License 2.0 | 5 votes |
/** * 1. Signs a string with a secret key using SHA-1 2. Base64 encode the result 3. URL encode the final result * * @param request * @param key * @return */ private static String signRequest(String request, String key) { try { Mac mac = Mac.getInstance("HmacSHA1"); SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "HmacSHA1"); mac.init(keySpec); mac.update(request.getBytes()); byte[] encryptedBytes = mac.doFinal(); return URLEncoder.encode(Base64.encodeBase64String(encryptedBytes), "UTF-8"); } catch (Exception ex) { s_logger.error(ex.getMessage()); return null; } }
Example #28
Source File: SM4Util.java From gmhelper with Apache License 2.0 | 5 votes |
/** * @param key * @param iv * @param padding 可以传null,传null表示NoPadding,由调用方保证数据必须是BlockSize的整数倍 * @param data * @return * @throws Exception */ public static byte[] doCBCMac(byte[] key, byte[] iv, BlockCipherPadding padding, byte[] data) throws Exception { SM4Engine engine = new SM4Engine(); if (padding == null) { if (data.length % engine.getBlockSize() != 0) { throw new Exception("if no padding, data length must be multiple of SM4 BlockSize"); } } org.bouncycastle.crypto.Mac mac = new CBCBlockCipherMac(engine, engine.getBlockSize() * 8, padding); return doMac(mac, key, iv, data); }
Example #29
Source File: MacUtil.java From Jose4j with Apache License 2.0 | 5 votes |
public static void initMacWithKey(Mac mac, Key key) throws org.jose4j.lang.InvalidKeyException { try { mac.init(key); } catch (InvalidKeyException e) { throw new org.jose4j.lang.InvalidKeyException("Key is not valid for " + mac.getAlgorithm(), e); } }
Example #30
Source File: MainActivity.java From android-sqrl with GNU General Public License v3.0 | 5 votes |
public static byte[] CreatePrivateKey(String domain, byte[] key) { byte[] hmac=null; try { SecretKeySpec pKey = new SecretKeySpec(key, "HmacSHA256"); Mac mac = Mac.getInstance("HmacSHA256"); mac.init(pKey); hmac = mac.doFinal(domain.getBytes()); } catch (Exception e) { } return hmac; }