List of usage examples for javax.crypto.spec SecretKeySpec SecretKeySpec
public SecretKeySpec(byte[] key, String algorithm)
From source file:au.com.borner.salesforce.client.rest.domain.LoginResponse.java
public void verify(String consumerSecret) { SecretKey hmacKey = null;/*from www . j ava 2 s. com*/ try { byte[] key = consumerSecret.getBytes(); hmacKey = new SecretKeySpec(key, ALGORITHM); Mac mac = Mac.getInstance(ALGORITHM); mac.init(hmacKey); byte[] digest = mac.doFinal((getIdUrl() + getIssuedAt()).getBytes()); byte[] decode_sig = new Base64(true).decode(getSignature()); if (!Arrays.equals(digest, decode_sig)) { throw new SecurityException("Signature could not be verified!"); } } catch (NoSuchAlgorithmException e) { throw new SecurityException(String.format( "Algorithm not found while trying to verifying signature: algorithm=%s; message=%s", ALGORITHM, e.getMessage()), e); } catch (InvalidKeyException e) { throw new SecurityException( String.format("Invalid key encountered while trying to verify signature: key=%s; message=%s", hmacKey, e.getMessage()), e); } }
From source file:com.ro.ssc.app.client.licensing.TrialKeyGenerator.java
public static String generateKey(String toEncode) { String encoded = ""; try {// ww w. java2s. c o m byte[] saltEncrypt = SALT_ENCRYPT.getBytes(); SecretKeyFactory factoryKeyEncrypt = SecretKeyFactory.getInstance(SECRET_KEY_FACTORY); SecretKey tmp = factoryKeyEncrypt.generateSecret( new PBEKeySpec(PASS_ENCRYPT.toCharArray(), saltEncrypt, ITERATIONS_ENCRYPT, KEY_LENGTH)); SecretKeySpec encryptKey = new SecretKeySpec(tmp.getEncoded(), ALGORITHM); Cipher aesCipherEncrypt = Cipher.getInstance(CIPHER); aesCipherEncrypt.init(Cipher.ENCRYPT_MODE, encryptKey); byte[] bytes = StringUtils.getBytesUtf8(toEncode); byte[] encryptBytes = aesCipherEncrypt.doFinal(bytes); encoded = Base64.encodeBase64URLSafeString(encryptBytes); } catch (Exception e) { e.printStackTrace(); } return encoded; }
From source file:com.adyen.Util.HMACValidator.java
public String calculateHMAC(String data, String key) throws java.security.SignatureException { try {//from ww w . j ava 2 s . c o m byte[] rawKey = Hex.decodeHex(key.toCharArray()); // Create an hmac_sha256 key from the raw key bytes SecretKeySpec signingKey = new SecretKeySpec(rawKey, HMAC_SHA256_ALGORITHM); // Get an hmac_sha256 Mac instance and initialize with the signing // key Mac mac = Mac.getInstance(HMAC_SHA256_ALGORITHM); mac.init(signingKey); // Compute the hmac on input data bytes byte[] rawHmac = mac.doFinal(data.getBytes(C_UTF8)); // Base64-encode the hmac return new String(Base64.encodeBase64(rawHmac)); } catch (Exception e) { throw new SignatureException("Failed to generate HMAC : " + e.getMessage()); } }
From source file:com.cisco.ca.cstg.pdi.services.license.LicenseCryptoServiceImpl.java
public void encryptToFile() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, IOException { BufferedWriter out = null;//from w w w .j a v a 2s . c o m try { byte[] raw = getPassword().getBytes(Charset.forName(Constants.UTF8)); SecretKeySpec skeySpec = new SecretKeySpec(raw, ALGORITHM_BLOWFISH); Cipher cipher = null; cipher = Cipher.getInstance(ALGORITHM_BLOWFISH); cipher.init(1, skeySpec); byte[] output = cipher.doFinal(getMetaData().getBytes()); BigInteger n = new BigInteger(output); String b64hidden = Base64.encodeBase64String(n.toString(16).getBytes()); setAssessmentKey(b64hidden); out = new BufferedWriter(new FileWriter(this.getAssessmentKeyFileName())); out.write(b64hidden); } finally { if (out != null) { out.close(); } } }
From source file:com.ec2box.manage.util.OTPUtil.java
/** * verifies code for OTP secret per time interval * * @param secret shared secret/* www. j a v a 2 s. com*/ * @param token verification token * @param time time representation to calculate OTP * @return true if success */ private static boolean verifyToken(String secret, long token, long time) { long calculated = -1; byte[] key = new Base32().decode(secret); SecretKeySpec secretKey = new SecretKeySpec(key, "HmacSHA1"); try { Mac mac = Mac.getInstance("HmacSHA1"); mac.init(secretKey); byte[] hash = mac.doFinal(ByteBuffer.allocate(8).putLong(time).array()); int offset = hash[hash.length - 1] & 0xF; for (int i = 0; i < 4; ++i) { calculated <<= 8; calculated |= (hash[offset + i] & 0xFF); } calculated &= 0x7FFFFFFF; calculated %= 1000000; } catch (Exception ex) { log.error(ex.toString(), ex); } return calculated != -1 && calculated == token; }
From source file:com.keybox.manage.util.OTPUtil.java
/** * verifies code for OTP secret per time interval * * @param secret shared secret// w w w . ja v a2s . c o m * @param token verification token * @param time time representation to calculate OTP * @return true if success */ private static boolean verifyToken(String secret, long token, long time) { long calculated = -1; byte[] key = new Base32().decode(secret); SecretKeySpec secretKey = new SecretKeySpec(key, "HmacSHA1"); try { Mac mac = Mac.getInstance("HmacSHA1"); mac.init(secretKey); byte[] hash = mac.doFinal(ByteBuffer.allocate(8).putLong(time).array()); int offset = hash[hash.length - 1] & 0xF; for (int i = 0; i < 4; ++i) { calculated <<= 8; calculated |= (hash[offset + i] & 0xFF); } calculated &= 0x7FFFFFFF; calculated %= 1000000; } catch (Exception ex) { log.error(ex.toString(), ex); } return (calculated != -1 && calculated == token); }
From source file:com.jk.security.JKEncDec.java
/** * Decrypt.//from w ww . j ava 2 s .c o m * * @param cipherText * the cipher text * @return the string */ public static String decrypt(String cipherText) { try { byte[] cipherBytes = toBytes(cipherText); Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", "SunJCE"); SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), "AES"); cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(IV.getBytes("UTF-8"))); return new String(cipher.doFinal(cipherBytes), "UTF-8").trim(); } catch (Exception e) { throw new JKSecurityException(e); } }
From source file:it.latraccia.pkcs11.reader.util.AESUtil.java
public static String decryptString(String encryptedText, String password) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { String decrypted = null;// w w w. j av a 2 s .c om byte[] key = password.getBytes(); if (key.length != 16) { throw new IllegalArgumentException("Invalid key size."); } byte[] value = Base64.decodeBase64(encryptedText); // Decrypt with AES/CBC/PKCS5Padding SecretKeySpec skeySpec = new SecretKeySpec(key, "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, skeySpec, new IvParameterSpec(new byte[16])); byte[] original = cipher.doFinal(value); decrypted = new String(original); return decrypted; }
From source file:com.enviosya.client.tool.Tool.java
public String Desencriptar(String textoEncriptado) throws Exception { //String secretKey = "qualityinfosolutions"; //llave para desenciptar datos String base64EncryptedString = ""; try {//w ww . ja va2 s. c o m byte[] message = Base64.decodeBase64(textoEncriptado.getBytes("utf-8")); MessageDigest md = MessageDigest.getInstance("MD5"); byte[] digestOfPassword = md.digest(secretKey.getBytes("utf-8")); byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24); SecretKey key = new SecretKeySpec(keyBytes, "DESede"); Cipher decipher = Cipher.getInstance("DESede"); decipher.init(Cipher.DECRYPT_MODE, key); byte[] plainText = decipher.doFinal(message); base64EncryptedString = new String(plainText, "UTF-8"); } catch (Exception e) { //Ac tengo que agregar el retorno de la exception } return base64EncryptedString; }
From source file:Main.java
static byte[] decryptJWE(String jwe, Key privRsaKey) { // Log.d("","decryptJWE"); try {//from w w w . ja v a2s . c om // split jwe string StringTokenizer tokens = new StringTokenizer(jwe, "."); int count = tokens.countTokens(); // Log.d("","parts.length: "+count); if (count != 5) return null; String jweProtectedHeader64 = tokens.nextToken(); String jweEncrypted64 = tokens.nextToken(); String jweInitVector64 = tokens.nextToken(); String cryptedBytes64 = tokens.nextToken(); String auth_tag64 = tokens.nextToken(); // decrypt cek using private rsa key byte[] cek = decryptRsaB64(jweEncrypted64, privRsaKey); // check cek result byte array if (cek == null || cek.length == 0 || (cek.length % 2) != 0) return null; int keySize = cek.length / 2; Log.d("", "Decryption AES: " + keySize * 8); // build aes_key and hmac_key byte aes_key[] = new byte[keySize]; byte hmac_key[] = new byte[keySize]; System.arraycopy(cek, 0, hmac_key, 0, keySize); System.arraycopy(cek, keySize, aes_key, 0, keySize); // decode initialization vector byte[] iv_key = decodeB64(jweInitVector64); Log.d("", "hmac_key: " + bytesToHex(hmac_key)); Log.d("", "aes_key: " + bytesToHex(aes_key)); Log.d("", "iv_key: " + bytesToHex(iv_key)); // decrypt content using aes_key and iv_key byte[] cryptedBytes = decodeB64(cryptedBytes64); Cipher decrypt = Cipher.getInstance("AES/CBC/PKCS5Padding", "SC"); decrypt.init(Cipher.DECRYPT_MODE, new SecretKeySpec(aes_key, "AES"), new IvParameterSpec(iv_key)); byte[] decryptedBytes = decrypt.doFinal(cryptedBytes); Log.d("", "decryptedBytes:"); Log.d("", bytesToHex(decryptedBytes)); // validation verification byte[] aad = jweProtectedHeader64.getBytes(); long al = aad.length * 8; // concatenate aad, iv_key, cryptedBytes and al byte[] hmacData = new byte[aad.length + iv_key.length + cryptedBytes.length + 8]; int offset = 0; System.arraycopy(aad, offset, hmacData, 0, aad.length); offset += aad.length; System.arraycopy(iv_key, 0, hmacData, offset, iv_key.length); offset += iv_key.length; System.arraycopy(cryptedBytes, 0, hmacData, offset, cryptedBytes.length); offset += cryptedBytes.length; ByteBuffer buffer = ByteBuffer.allocate(8); buffer.putLong(al); System.arraycopy(buffer.array(), 0, hmacData, offset, 8); // compute hmac Mac hmac = Mac.getInstance("HmacSHA256", "SC"); hmac.init(new SecretKeySpec(hmac_key, "HmacSHA256")); byte[] hmacValue = hmac.doFinal(hmacData); // pick authentication tag byte[] authTag = Arrays.copyOf(hmacValue, 16); // validate authentication tag byte[] authTagRead = decodeB64(auth_tag64); for (int i = 0; i < 16; i++) { if (authTag[i] != authTagRead[i]) { Log.d("", "validation failed"); return decryptedBytes; } } Log.d("", "validation success"); // validation success return decryptedBytes; } catch (Exception e) { e.printStackTrace(); } return null; }