List of usage examples for javax.crypto Mac init
public final void init(Key key) throws InvalidKeyException
From source file:com.here.account.auth.SignatureCalculator.java
private String generateSignature(String signatureBaseString, String signatureMethod) { try {//from w ww.java 2s . co m //get the bytes from the signature base string byte[] bytesToSign = signatureBaseString.getBytes(OAuthConstants.UTF_8_CHARSET); //create the signing key from the clientSecret byte[] keyBytes = (urlEncode(consumerSecret) + "&").getBytes(OAuthConstants.UTF_8_CHARSET); SecretKeySpec signingKey = new SecretKeySpec(keyBytes, signatureMethod); //generate signature based on the requested signature method Mac mac = Mac.getInstance(signatureMethod); mac.init(signingKey); byte[] signedBytes = mac.doFinal(bytesToSign); return Base64.encodeBase64String(signedBytes); } catch (Exception e) { throw new IllegalArgumentException(e); } }
From source file:com.sk89q.craftapi.streaming.StreamingServerClient.java
/** * Handle unauthenticated packets./*from w w w. j av a 2 s. co m*/ * * @param parts */ public void handleUnauthenticated(String[] parts) throws UnsupportedEncodingException { String command = decode(parts[0]); // getChallenge if (command.equals("REQC")) { send("CHAL", base64.encodeToString(challenge)); // challengeLogin } else if (command.equals("AUTH")) { try { SecretKey key = new SecretKeySpec(challenge, "HMACSHA256"); Mac mac = Mac.getInstance("HMACSHA256"); mac.init(key); byte[] digest = base64.decode(decode(parts[3]).getBytes()); if (server.getAuthenticationProvider().verifyCredentials(mac, parts[2], digest)) { send("AUTHOK"); state = State.READY; } else { sendError(ERROR_AUTHENTICATION); } } catch (NoSuchAlgorithmException e) { sendError(ERROR_INTERNAL, e.getMessage()); } catch (InvalidKeyException e) { sendError(ERROR_INTERNAL, e.getMessage()); } // Unknown } else { sendError(ERROR_UNKNOWN_PACKET, command); } }
From source file:org.apache.hadoop.hdfs.security.AccessTokenHandler.java
/** Initialize Mac function */ private synchronized void initMac(BlockAccessKey key) throws IOException { try {//from w w w .ja v a 2 s.c o m Mac mac = Mac.getInstance("HmacSHA1"); mac.init(new SecretKeySpec(key.getKey().getBytes(), "HmacSHA1")); key.setMac(mac); } catch (GeneralSecurityException e) { throw (IOException) new IOException("Failed to initialize Mac for access key, keyID=" + key.getKeyID()) .initCause(e); } }
From source file:org.basinmc.irc.bridge.github.GitHubServerHandler.java
/** * Verifies a request signature.//from w w w. jav a 2s . c o m * * @param data a payload. * @param signature a signature. * @return true if valid, false otherwise. */ private boolean verifySignature(@Nonnull String data, @Nonnull String signature) { if (this.secret == null) { logger.warn("No secret key specified. Signature checks will be skipped!"); return true; } try { Mac mac = Mac.getInstance(SIGNATURE_ALGORITHM); mac.init(this.secret); byte[] expected = mac.doFinal(data.getBytes(StandardCharsets.UTF_8)); return Arrays.equals(expected, Hex.decodeHex(signature.toCharArray())); } catch (InvalidKeyException | NoSuchAlgorithmException ex) { logger.error("Could not verify signature: " + ex.getMessage(), ex); } catch (DecoderException ex) { logger.warn("Could not decode signature: " + ex.getMessage(), ex); } throw new IllegalStateException("Could not verify signature"); }
From source file:hudson.plugins.sauce_ondemand.PluginImpl.java
/** * Creates a HMAC token which is used as part of the Javascript inclusion that embeds the Sauce results * * @param username the Sauce user id//from w ww .j a v a2 s .c o m * @param accessKey the Sauce access key * @param jobId the Sauce job id * @return the HMAC token * @throws java.security.NoSuchAlgorithmException * * @throws java.security.InvalidKeyException * * @throws java.io.UnsupportedEncodingException * */ public String calcHMAC(String username, String accessKey, String jobId) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException { Calendar calendar = Calendar.getInstance(); SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT); format.setTimeZone(TimeZone.getTimeZone("UTC")); String key = username + ":" + accessKey + ":" + format.format(calendar.getTime()); byte[] keyBytes = key.getBytes(); SecretKeySpec sks = new SecretKeySpec(keyBytes, HMAC_KEY); Mac mac = Mac.getInstance(sks.getAlgorithm()); mac.init(sks); byte[] hmacBytes = mac.doFinal(jobId.getBytes()); byte[] hexBytes = new Hex().encode(hmacBytes); return new String(hexBytes, "ISO-8859-1"); }
From source file:de.burlov.ultracipher.core.mail.AuthenticatingSMTPClient.java
/** * Authenticate to the SMTP server by sending the AUTH command with the * selected mechanism, using the given username and the given password. * <p/>/*from w w w .j a v a2s.c o m*/ * * @return True if successfully completed, false if not. * @throws SMTPConnectionClosedException If the SMTP server prematurely closes the connection as a * result of the client being idle or some other reason * causing the server to send SMTP reply code 421. This * exception may be caught either as an IOException or * independently as itself. * @throws java.io.IOException If an I/O error occurs while either sending a command to * the server or receiving a reply from the server. * @throws java.security.NoSuchAlgorithmException If the CRAM hash algorithm cannot be instantiated by the * Java runtime system. * @throws java.security.InvalidKeyException If the CRAM hash algorithm failed to use the given * password. * @throws java.security.spec.InvalidKeySpecException If the CRAM hash algorithm failed to use the given * password. * * */ public boolean auth(AUTH_METHOD method, String username, String password) throws IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException { if (!SMTPReply.isPositiveIntermediate(sendCommand(SMTPCommand.AUTH, AUTH_METHOD.getAuthName(method)))) { return false; } if (method.equals(AUTH_METHOD.PLAIN)) { // the server sends an empty response ("334 "), so we don't have to // read it. return SMTPReply.isPositiveCompletion(sendCommand( new String(Base64.encodeBase64(("\000" + username + "\000" + password).getBytes())))); } else if (method.equals(AUTH_METHOD.CRAM_MD5)) { // get the CRAM challenge byte[] serverChallenge = Base64.decodeBase64(getReplyString().substring(4).trim()); // get the Mac instance Mac hmac_md5 = Mac.getInstance("HmacMD5"); hmac_md5.init(new SecretKeySpec(password.getBytes(), "HmacMD5")); // compute the result: byte[] hmacResult = _convertToHexString(hmac_md5.doFinal(serverChallenge)).getBytes(); // join the byte arrays to form the reply byte[] usernameBytes = username.getBytes(); byte[] toEncode = new byte[usernameBytes.length + 1 /* the space */ + hmacResult.length]; System.arraycopy(usernameBytes, 0, toEncode, 0, usernameBytes.length); toEncode[usernameBytes.length] = ' '; System.arraycopy(hmacResult, 0, toEncode, usernameBytes.length + 1, hmacResult.length); // send the reply and read the server code: return SMTPReply.isPositiveCompletion(sendCommand(new String(Base64.encodeBase64(toEncode)))); } else if (method.equals(AUTH_METHOD.LOGIN)) { // the server sends fixed responses (base64("Username") and // base64("Password")), so we don't have to read them. if (!SMTPReply .isPositiveIntermediate(sendCommand(new String(Base64.encodeBase64(username.getBytes()))))) { return false; } return SMTPReply .isPositiveCompletion(sendCommand(new String(Base64.encodeBase64(password.getBytes())))); } else { return false; // safety check } }
From source file:org.cryptonode.jncryptor.AES256v2Cryptor.java
/** * Decrypts data./* ww w . ja v a 2s .com*/ * * @param aesCiphertext * the ciphertext from the message * @param decryptionKey * the key to decrypt * @param hmacKey * the key to recalculate the HMAC * @return the decrypted data * @throws CryptorException * if a JCE error occurs */ private byte[] decryptData(AES256v2Ciphertext aesCiphertext, SecretKey decryptionKey, SecretKey hmacKey) throws CryptorException { try { Mac mac = Mac.getInstance(HMAC_ALGORITHM); mac.init(hmacKey); byte[] hmacValue = mac.doFinal(aesCiphertext.getDataToHMAC()); if (!Arrays.equals(hmacValue, aesCiphertext.getHmac())) { throw new InvalidHMACException("Incorrect HMAC value."); } Cipher cipher = Cipher.getInstance(AES_CIPHER_ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, decryptionKey, new IvParameterSpec(aesCiphertext.getIv())); return cipher.doFinal(aesCiphertext.getCiphertext()); } catch (GeneralSecurityException e) { throw new CryptorException("Failed to decrypt message.", e); } }
From source file:com.epl.ticketws.services.QueryService.java
/** * Signs a string with the given key./* w w w. j a v a 2s.c o m*/ * * @param data * @param key * @return * @throws SignatureException */ private String generate_HMAC_SHA1_Signature(String data, String key) throws SignatureException { String result; try { // get an hmac_sha1 key from the raw key bytes SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(UTF_8), 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(UTF_8)); //byte[] base64 = Base64.encodeBase64(rawHmac); byte[] base64 = Base64.getEncoder().encode(rawHmac); // base64-encode the hmac result = new String(base64); } catch (Exception e) { throw new SignatureException("Failed to generate HMAC : " + e.getMessage()); } return AUTHORIZATION_HEADER_HMAC_PREFIX + result; }
From source file:com.hp.autonomy.hod.client.util.Hmac.java
private byte[] hmacSha1(final String message, final String secret) { try {//from w ww . j a va 2 s . c om final Mac mac = Mac.getInstance(HMAC_SHA1); final Key key = new SecretKeySpec(bytesFromString(secret), HMAC_SHA1); mac.init(key); return mac.doFinal(bytesFromString(message)); } catch (final NoSuchAlgorithmException e) { // This should never happen on a sensible JVM throw new AssertionError("HMAC SHA1 is not supported", e); } catch (final InvalidKeyException e) { // In practice, this means that the token secret was invalid throw new IllegalArgumentException("Invalid token secret", e); } }
From source file:org.cryptonode.jncryptor.AES256v2Cryptor.java
/** * Encrypts plaintext data, 256-bit AES CBC-mode with PKCS#5 padding. * // w w w . jav a 2 s . c om * @param plaintext * the plaintext * @param password * the password (can be <code>null</code> or empty) * @param encryptionSalt * eight bytes of random salt value * @param hmacSalt * eight bytes of random salt value * @param iv * sixteen bytes of AES IV * @return a formatted ciphertext * @throws CryptorException * if an error occurred */ byte[] encryptData(byte[] plaintext, char[] password, byte[] encryptionSalt, byte[] hmacSalt, byte[] iv) throws CryptorException { SecretKey encryptionKey = keyForPassword(password, encryptionSalt); SecretKey hmacKey = keyForPassword(password, hmacSalt); try { Cipher cipher = Cipher.getInstance(AES_CIPHER_ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, encryptionKey, new IvParameterSpec(iv)); byte[] ciphertext = cipher.doFinal(plaintext); AES256v2Ciphertext output = new AES256v2Ciphertext(encryptionSalt, hmacSalt, iv, ciphertext); Mac mac = Mac.getInstance(HMAC_ALGORITHM); mac.init(hmacKey); byte[] hmac = mac.doFinal(output.getDataToHMAC()); output.setHmac(hmac); return output.getRawData(); } catch (GeneralSecurityException e) { throw new CryptorException("Failed to generate ciphertext.", e); } }