List of usage examples for java.security InvalidKeyException getMessage
public String getMessage()
From source file:org.gss_project.gss.web.client.TestClient.java
public static String sign(String httpMethod, String timestamp, String path, String token) { String input = httpMethod + timestamp + path; String signed = null;//from w w w . j av a2 s. co m try { System.err.println("Token:" + token); // Get an HMAC-SHA1 key from the authentication token. System.err.println("Input: " + input); SecretKeySpec signingKey = new SecretKeySpec(Base64.decodeBase64(token.getBytes()), "HmacSHA1"); // Get an HMAC-SHA1 Mac instance and initialize with the signing key. Mac hmac = Mac.getInstance("HmacSHA1"); hmac.init(signingKey); // Compute the HMAC on the input data bytes. byte[] rawMac = hmac.doFinal(input.getBytes()); // Do base 64 encoding. signed = new String(Base64.encodeBase64(rawMac), "US-ASCII"); } catch (InvalidKeyException ikex) { System.err.println("Fatal key exception: " + ikex.getMessage()); ikex.printStackTrace(); } catch (UnsupportedEncodingException ueex) { System.err.println("Fatal encoding exception: " + ueex.getMessage()); } catch (NoSuchAlgorithmException nsaex) { System.err.println("Fatal algorithm exception: " + nsaex.getMessage()); nsaex.printStackTrace(); } if (signed == null) System.exit(-1); System.err.println("Signed: " + signed); return signed; }
From source file:edu.internet2.middleware.openid.security.SecurityUtils.java
/** * Calculate signature for specified data using an Association. * // w w w . jav a 2 s .c o m * @param association association * @param data data to calculate signature for * @return calculated signature * @throws SecurityException if unable to calculate the signature */ public static String calculateSignature(Association association, String data) throws SecurityException { log.debug("calculating signature using association: {}", association.getHandle()); log.debug("signature data = {}", data); try { Mac mac = Mac.getInstance(association.getMacKey().getAlgorithm()); mac.init(association.getMacKey()); byte[] rawHmac = mac.doFinal(data.getBytes()); return new String(Base64.encodeBase64(rawHmac)); } catch (InvalidKeyException e) { log.error("Unable to generate MAC - " + e.getMessage()); throw new SecurityException("Unable to generate MAC", e); } catch (NoSuchAlgorithmException e) { log.error("Unable to generate MAC - " + e.getMessage()); throw new SecurityException("Unable to generate MAC", e); } }
From source file:org.apache.http.contrib.auth.AWSScheme.java
/** * Computes RFC 2104-compliant HMAC signature. * * @param data/*from w w w . j av a 2s . c om*/ * The data to be signed. * @param key * The signing key. * @return The Base64-encoded RFC 2104-compliant HMAC signature. * @throws RuntimeException * when signature generation fails */ private static String calculateRFC2104HMAC(final String data, final String key) throws AuthenticationException { try { // get an hmac_sha1 key from the raw key bytes SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), 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()); // base64-encode the hmac return Base64.encodeBase64String(rawHmac); } catch (InvalidKeyException ex) { throw new AuthenticationException("Failed to generate HMAC: " + ex.getMessage(), ex); } catch (NoSuchAlgorithmException ex) { throw new AuthenticationException(HMAC_SHA1_ALGORITHM + " algorithm is not supported", ex); } }
From source file:com.cws.esolutions.security.utils.PasswordUtils.java
/** * Provides two-way (reversible) encryption of a provided string. Can be used where reversibility * is required but encryption (obfuscation, technically) is required. * * @param value - The plain text data to encrypt * @param salt - The salt value to utilize for the request * @param secretInstance - The cryptographic instance to use for the SecretKeyFactory * @param iterations - The number of times to loop through the keyspec * @param keyBits - The size of the key, in bits * @param algorithm - The algorithm to encrypt the data with * @param cipherInstance - The cipher instance to utilize * @param encoding - The text encoding// www . j a va 2 s . c o m * @return The encrypted string in a reversible format * @throws SecurityException {@link java.lang.SecurityException} if an exception occurs during processing */ public static final String decryptText(final String value, final String salt, final String secretInstance, final int iterations, final int keyBits, final String algorithm, final String cipherInstance, final String encoding) throws SecurityException { final String methodName = PasswordUtils.CNAME + "#encryptText(final String value, final String salt, final String secretInstance, final int iterations, final int keyBits, final String algorithm, final String cipherInstance, final String encoding) throws SecurityException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", secretInstance); DEBUGGER.debug("Value: {}", iterations); DEBUGGER.debug("Value: {}", keyBits); DEBUGGER.debug("Value: {}", algorithm); DEBUGGER.debug("Value: {}", cipherInstance); DEBUGGER.debug("Value: {}", encoding); } String decPass = null; try { String decoded = new String(Base64.getDecoder().decode(value)); String iv = decoded.split(":")[0]; String property = decoded.split(":")[1]; SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(secretInstance); PBEKeySpec keySpec = new PBEKeySpec(salt.toCharArray(), salt.getBytes(), iterations, keyBits); SecretKey keyTmp = keyFactory.generateSecret(keySpec); SecretKeySpec sks = new SecretKeySpec(keyTmp.getEncoded(), algorithm); Cipher pbeCipher = Cipher.getInstance(cipherInstance); pbeCipher.init(Cipher.DECRYPT_MODE, sks, new IvParameterSpec(Base64.getDecoder().decode(iv))); decPass = new String(pbeCipher.doFinal(Base64.getDecoder().decode(property)), encoding); } catch (InvalidKeyException ikx) { throw new SecurityException(ikx.getMessage(), ikx); } catch (NoSuchAlgorithmException nsx) { throw new SecurityException(nsx.getMessage(), nsx); } catch (NoSuchPaddingException npx) { throw new SecurityException(npx.getMessage(), npx); } catch (IllegalBlockSizeException ibx) { throw new SecurityException(ibx.getMessage(), ibx); } catch (BadPaddingException bpx) { throw new SecurityException(bpx.getMessage(), bpx); } catch (UnsupportedEncodingException uex) { throw new SecurityException(uex.getMessage(), uex); } catch (InvalidAlgorithmParameterException iapx) { throw new SecurityException(iapx.getMessage(), iapx); } catch (InvalidKeySpecException iksx) { throw new SecurityException(iksx.getMessage(), iksx); } return decPass; }
From source file:com.cws.esolutions.security.utils.PasswordUtils.java
/** * Base64 decodes a given string//from w ww . java2 s . c o m * * @param variance - The allowed differences in OTP values * @param algorithm - The algorithm to encrypt the data with * @param instance - The security instance to utilize * @param secret - The OTP secret * @param code - The OTP code * @return <code>true</code> if successful, <code>false</code> otherwise * @throws SecurityException {@link java.lang.SecurityException} if an exception occurs during processing */ public static final boolean validateOtpValue(final int variance, final String algorithm, final String instance, final String secret, final int code) throws SecurityException { final String methodName = PasswordUtils.CNAME + "#validateOtpValue(final int variance, final String algorithm, final String instance, final String secret, final int code) throws SecurityException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", variance); DEBUGGER.debug("Value: {}", algorithm); DEBUGGER.debug("Value: {}", instance); DEBUGGER.debug("Value: {}", secret); DEBUGGER.debug("Value: {}", code); } long truncatedHash = 0; byte[] data = new byte[8]; long timeIndex = System.currentTimeMillis() / 1000 / 30; final Base32 codec = new Base32(); final byte[] decoded = codec.decode(secret); SecretKeySpec signKey = new SecretKeySpec(decoded, algorithm); if (DEBUG) { DEBUGGER.debug("long: {}", timeIndex); } try { for (int i = 8; i-- > 0; timeIndex >>>= 8) { data[i] = (byte) timeIndex; } Mac mac = Mac.getInstance(instance); mac.init(signKey); byte[] hash = mac.doFinal(data); int offset = hash[20 - 1] & 0xF; for (int i = 0; i < 4; i++) { truncatedHash <<= 8; truncatedHash |= (hash[offset + i] & 0xFF); } truncatedHash &= 0x7FFFFFFF; truncatedHash %= 1000000; if (DEBUG) { DEBUGGER.debug("truncatedHash: {}", truncatedHash); } return (truncatedHash == code); } catch (InvalidKeyException ikx) { throw new SecurityException(ikx.getMessage(), ikx); } catch (NoSuchAlgorithmException nsx) { throw new SecurityException(nsx.getMessage(), nsx); } }
From source file:com.cws.esolutions.security.utils.PasswordUtils.java
/** * Provides two-way (reversible) encryption of a provided string. Can be used where reversibility * is required but encryption (obfuscation, technically) is required. * * @param value - The plain text data to encrypt * @param salt - The salt value to utilize for the request * @param secretInstance - The cryptographic instance to use for the SecretKeyFactory * @param iterations - The number of times to loop through the keyspec * @param keyBits - The size of the key, in bits * @param algorithm - The algorithm to encrypt the data with * @param cipherInstance - The cipher instance to utilize * @param encoding - The text encoding/*from w w w . j a v a 2 s . c o m*/ * @return The encrypted string in a reversible format * @throws SecurityException {@link java.lang.SecurityException} if an exception occurs during processing */ public static final String encryptText(final String value, final String salt, final String secretInstance, final int iterations, final int keyBits, final String algorithm, final String cipherInstance, final String encoding) throws SecurityException { final String methodName = PasswordUtils.CNAME + "#encryptText(final String value, final String salt, final String secretInstance, final int iterations, final int keyBits, final String algorithm, final String cipherInstance, final String encoding) throws SecurityException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", secretInstance); DEBUGGER.debug("Value: {}", iterations); DEBUGGER.debug("Value: {}", keyBits); DEBUGGER.debug("Value: {}", algorithm); DEBUGGER.debug("Value: {}", cipherInstance); DEBUGGER.debug("Value: {}", encoding); } String encPass = null; try { SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(secretInstance); PBEKeySpec keySpec = new PBEKeySpec(salt.toCharArray(), salt.getBytes(), iterations, keyBits); SecretKey keyTmp = keyFactory.generateSecret(keySpec); SecretKeySpec sks = new SecretKeySpec(keyTmp.getEncoded(), algorithm); Cipher pbeCipher = Cipher.getInstance(cipherInstance); pbeCipher.init(Cipher.ENCRYPT_MODE, sks); AlgorithmParameters parameters = pbeCipher.getParameters(); IvParameterSpec ivParameterSpec = parameters.getParameterSpec(IvParameterSpec.class); byte[] cryptoText = pbeCipher.doFinal(value.getBytes(encoding)); byte[] iv = ivParameterSpec.getIV(); String combined = Base64.getEncoder().encodeToString(iv) + ":" + Base64.getEncoder().encodeToString(cryptoText); encPass = Base64.getEncoder().encodeToString(combined.getBytes()); } catch (InvalidKeyException ikx) { throw new SecurityException(ikx.getMessage(), ikx); } catch (NoSuchAlgorithmException nsx) { throw new SecurityException(nsx.getMessage(), nsx); } catch (NoSuchPaddingException npx) { throw new SecurityException(npx.getMessage(), npx); } catch (IllegalBlockSizeException ibx) { throw new SecurityException(ibx.getMessage(), ibx); } catch (BadPaddingException bpx) { throw new SecurityException(bpx.getMessage(), bpx); } catch (UnsupportedEncodingException uex) { throw new SecurityException(uex.getMessage(), uex); } catch (InvalidKeySpecException iksx) { throw new SecurityException(iksx.getMessage(), iksx); } catch (InvalidParameterSpecException ipsx) { throw new SecurityException(ipsx.getMessage(), ipsx); } return encPass; }
From source file:org.signserver.server.cryptotokens.CryptoTokenHelper.java
/** * Performs test signatures for the specified keys or for all if "all" specified. * @param keyStore Loaded keystore to read keys from * @param alias Alias of key to test or "all" to test all * @param authCode Key password (if used, ie for JKS only) * @param signatureProvider Provider for creating the signature * @return The results for each key found * @throws CryptoTokenOfflineException In case the key could not be used *//*from w ww.j a v a 2 s . c o m*/ public static Collection<KeyTestResult> testKey(KeyStore keyStore, String alias, char[] authCode, String signatureProvider) throws CryptoTokenOfflineException { if (LOG.isDebugEnabled()) { LOG.debug("testKey for alias: " + alias); } final Collection<KeyTestResult> result = new LinkedList<KeyTestResult>(); try { final Enumeration<String> e = keyStore.aliases(); while (e.hasMoreElements()) { final String keyAlias = e.nextElement(); if (alias.equalsIgnoreCase(ICryptoToken.ALL_KEYS) || alias.equals(keyAlias)) { if (LOG.isDebugEnabled()) { LOG.debug("checking keyAlias: " + keyAlias); } if (keyStore.isKeyEntry(keyAlias)) { String status; String publicKeyHash = null; boolean success = false; try { final PrivateKey privateKey = (PrivateKey) keyStore.getKey(keyAlias, authCode); final Certificate entryCert = keyStore.getCertificate(keyAlias); if (entryCert != null) { final PublicKey publicKey = entryCert.getPublicKey(); publicKeyHash = createKeyHash(publicKey); testSignAndVerify(privateKey, publicKey, signatureProvider); success = true; status = ""; } else { status = "Not testing keys with alias " + keyAlias + ". No certificate exists."; } } catch (ClassCastException ce) { status = "Not testing keys with alias " + keyAlias + ". Not a private key."; } catch (InvalidKeyException ex) { LOG.error("Error testing key: " + keyAlias, ex); status = ex.getMessage(); } catch (KeyStoreException ex) { LOG.error("Error testing key: " + keyAlias, ex); status = ex.getMessage(); } catch (NoSuchAlgorithmException ex) { LOG.error("Error testing key: " + keyAlias, ex); status = ex.getMessage(); } catch (NoSuchProviderException ex) { LOG.error("Error testing key: " + keyAlias, ex); status = ex.getMessage(); } catch (SignatureException ex) { LOG.error("Error testing key: " + keyAlias, ex); status = ex.getMessage(); } catch (UnrecoverableKeyException ex) { LOG.error("Error testing key: " + keyAlias, ex); status = ex.getMessage(); } result.add(new KeyTestResult(keyAlias, success, status, publicKeyHash)); } } } } catch (KeyStoreException ex) { throw new CryptoTokenOfflineException(ex); } if (LOG.isDebugEnabled()) { LOG.debug("<testKey"); } return result; }
From source file:vc.fq.FanfouExporter.ExportTread.java
/** * Computes RFC 2104-compliant HMAC signature. * @author Yusuke Yamamoto - yusuke at mac.com * @edit Unicorn-Feng/*from ww w. j a va2s . c o m*/ * @see <a href="http://oauth.net/core/1.0/">OAuth Core 1.0</a> * @param data the data to be signed * @param access token secret * @return signature * @see <a href="http://oauth.net/core/1.0/#rfc.section.9.2.1">OAuth Core - 9.2.1. Generating Signature</a> */ public static String generateSignature(String data, String token) { byte[] byteHMAC = null; try { Mac mac = Mac.getInstance(HMAC_SHA1); SecretKeySpec spec; if (token == null) { String oauthSignature = encode(consumer_secret) + "&"; spec = new SecretKeySpec(oauthSignature.getBytes(), HMAC_SHA1); } else { String oauthSignature = encode(consumer_secret) + "&" + encode(token); spec = new SecretKeySpec(oauthSignature.getBytes(), HMAC_SHA1); } mac.init(spec); byteHMAC = mac.doFinal(data.getBytes()); } catch (InvalidKeyException e) { setLog(e.getMessage()); } catch (NoSuchAlgorithmException ignore) { // should never happen } try { return URLEncoder.encode(BASE64Encoder.encode(byteHMAC), "UTF-8"); } catch (UnsupportedEncodingException e) { setLog("?"); } return null; }
From source file:org.xlcloud.encryption.AESEncryptionService.java
/** {@inheritDoc} */ public String decrypt(String encryptedMessage) throws EncryptionException { try {//from w ww. ja v a2 s . co m Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, buildEncryptionKey()); byte[] decrypted = cipher.doFinal(Base64.decodeBase64(encryptedMessage)); return new String(decrypted, ENCODING); } catch (InvalidKeyException e) { LOG.error(e.getMessage()); throw new EncryptionException(e.getMessage(), e); } catch (UnsupportedEncodingException e) { LOG.error(e.getMessage()); throw new EncryptionException(e.getMessage(), e); } catch (NoSuchAlgorithmException e) { LOG.error(e.getMessage()); throw new EncryptionException(e.getMessage(), e); } catch (NoSuchPaddingException e) { LOG.error(e.getMessage()); throw new EncryptionException(e.getMessage(), e); } catch (IllegalBlockSizeException e) { LOG.error(e.getMessage()); throw new EncryptionException(e.getMessage(), e); } catch (BadPaddingException e) { LOG.error(e.getMessage()); throw new EncryptionException(e.getMessage(), e); } }
From source file:com.redgate.hadoop.hive.azuretables.AzureTablesRecordReader.java
/** * Create a new Azure Table Reader/* w w w . j ava2 s . c o m*/ * * @param storageConnectionString * An Azure Table connection string, usually built from the * InputFormat * @param table * The name of the Azure table, specified in the Hive table * definition * @param split */ public AzureTablesRecordReader(String storageConnectionString, String table, InputSplit split) { AzureTablesSplit partitionSplit = (AzureTablesSplit) split; CloudStorageAccount storageAccount; try { storageAccount = CloudStorageAccount.parse(storageConnectionString); CloudTableClient tableClient = storageAccount.createCloudTableClient(); LOG.info(String.format("Connecting to Windows Azure Account: %s", storageAccount)); String partitionFilter = TableQuery.generateFilterCondition(TableConstants.PARTITION_KEY, QueryComparisons.EQUAL, partitionSplit.getPartitionKey()); TableQuery<DynamicTableEntity> partitionQuery = TableQuery.from(table, DynamicTableEntity.class) .where(partitionFilter); results = tableClient.execute(partitionQuery).iterator(); } catch (InvalidKeyException e) { LOG.error(e.getMessage()); } catch (URISyntaxException e) { LOG.error(e.getMessage()); } }