List of usage examples for java.security SignatureException SignatureException
public SignatureException(Throwable cause)
From source file:uk.ac.bbsrc.tgac.miso.core.security.ShaPasswordCodecService.java
/** * Encrypt a plaintext String using a hmac_sha1 salt * // w w w . j a v a 2 s .co m * @param key * of type String * @param plaintext * of type String * @return String the encrypted String of the given plaintext String * @throws java.security.SignatureException * when the HMAC is unable to be generated */ public synchronized String encryptHMACSHA1(String key, String plaintext) throws SignatureException { String result; try { // get an hmac_sha1 key from the raw key bytes SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), "HmacSHA1"); // get an hmac_sha1 Mac instance and initialize with the signing key Mac mac = Mac.getInstance("HmacSHA1"); mac.init(signingKey); // compute the hmac on input data bytes byte[] rawHmac = mac.doFinal(plaintext.getBytes()); // base64-encode the hmac result = new Base64().encodeToString(rawHmac); } catch (Exception e) { log.error("failed to generate HMAC", e); throw new SignatureException("Failed to generate HMAC : " + e.getMessage()); } return result; }
From source file:org.ejbca.extra.db.SubMessages.java
/** * Method use by db api to load a persisted submessage * @param cACertChain is the CA chain that signed the RA and CAService keystore * @param crls could be set to null to disable CRL checking *//*from ww w . jav a 2 s . com*/ void load(String data, PrivateKey userKey, Collection cACertChain, Collection crls) { try { submessages.clear(); java.beans.XMLDecoder decoder = new java.beans.XMLDecoder( new java.io.ByteArrayInputStream(data.getBytes("UTF8"))); isSigned = ((Boolean) decoder.readObject()).booleanValue(); isEncrypted = ((Boolean) decoder.readObject()).booleanValue(); byte[] messagedata = Base64.decode(((String) decoder.readObject()).getBytes()); decoder.close(); if (isEncrypted) { messagedata = ExtRAMsgHelper.decryptData(userKey, messagedata); } if (isSigned) { ParsedSignatureResult result = ExtRAMsgHelper.verifySignature(cACertChain, crls, messagedata); if (!result.isValid()) { throw new SignatureException("Signature not valid"); } this.signerCert = result.getSignerCert(); messagedata = result.getContent(); } ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(messagedata)); ArrayList<HashMap> savearray = (ArrayList<HashMap>) ois.readObject(); Iterator<HashMap> iter = savearray.iterator(); while (iter.hasNext()) { HashMap map = iter.next(); ISubMessage submessage = SubMessageFactory.createInstance(map); submessage.loadData(map); submessages.add(submessage); } ois.close(); } catch (Exception e) { log.error("Error reading persistent SubMessages.", e); } }
From source file:com.cloud.stack.CloudStackCommand.java
private String calculateRFC2104HMAC(String signIt, String secretKey) throws SignatureException { String result = null;/* ww w . j av a 2s. c om*/ try { SecretKeySpec key = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1"); Mac hmacSha1 = Mac.getInstance("HmacSHA1"); hmacSha1.init(key); byte[] rawHmac = hmacSha1.doFinal(signIt.getBytes()); result = new String(Base64.encodeBase64(rawHmac)); } catch (Exception e) { throw new SignatureException("Failed to generate keyed HMAC on soap request: " + e.getMessage()); } return result.trim(); }
From source file:com.amazonaws.ipnreturnurlvalidation.SignatureUtilsForOutbound.java
private boolean validateSignatureV1(Map<String, String> parameters) throws SignatureException { if (this.awsSecretKey == null) { throw new SignatureException("Signature can not be verified without aws secret key."); }// w w w . ja v a 2 s . com String stringToSign = calculateStringToSignV1(parameters); String signature = parameters.get(SIGNATURE_KEYNAME); String result; try { SecretKeySpec signingKey = new SecretKeySpec(this.awsSecretKey.getBytes(), "HmacSHA1"); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(signingKey); byte[] rawHmac = mac.doFinal(stringToSign.getBytes("UTF-8")); result = new String(Base64.encodeBase64(rawHmac)); } catch (NoSuchAlgorithmException e) { throw new SignatureException("Failed to generate HMAC : " + e.getMessage()); } catch (InvalidKeyException e) { throw new SignatureException("Failed to generate HMAC : " + e.getMessage()); } catch (UnsupportedEncodingException e) { throw new SignatureException("Failed to generate HMAC : " + e.getMessage()); } return result.equals(signature); }
From source file:com.appdynamics.cloudstack.CloudStackApiClient.java
public String calculateRFC2104HMAC(String data, String key) throws Exception { String result;// w ww. j a v a 2 s . c o m try { // get an hmac_sha1 key from the raw key bytes SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), "HmacSHA1"); // get an hmac_sha1 Mac instance and initialize with the signing key Mac mac = Mac.getInstance("HmacSHA1"); mac.init(signingKey); // compute the hmac on input data bytes byte[] rawHmac = mac.doFinal(data.getBytes()); // base64-encode the hmac // result = Base64.encode(rawHmac); result = new String(Base64.encodeBase64(rawHmac)); return result.trim(); } catch (Exception e) { throw new SignatureException("Failed to generate HMAC : " + e.getMessage()); } // return encodeUrl(result); }
From source file:org.cloudfoundry.identity.uaa.authentication.RubyUserTokenTests.java
/** * * @param token the token string containing the ruby-marshalled username, expiry time and HMAC signature * @param key Used to validate the signature of the token. * * @return a UserToken instance containing the data * @throws SignatureException if the signature in the token string does not match the one calculated using the * supplied key.//from w ww . j a va 2 s.c o m */ public static UserToken decode(String token, SecretKey key) throws SignatureException { ByteArrayInputStream bytes = new ByteArrayInputStream(Hex.decode(token)); try { UnmarshalStream stream = new UnmarshalStream(Ruby.getGlobalRuntime(), bytes, null, false); IRubyObject object = stream.unmarshalObject(); Assert.isInstanceOf(RubyArray.class, object); RubyArray array = (RubyArray) object; Assert.isTrue(array.size() == 3); String username = (String) array.get(0); Long validUntil = (Long) array.get(1); ByteList sigBytes = ((RubyString) array.eltOk(2)).getByteList(); // HexDumpEncoder enc = new HexDumpEncoder(); // System.out.println("Signature from token is: \n" + enc.encode(sigBytes.unsafeBytes())); UserToken ut = new UserToken(username, validUntil, key); if (!Arrays.equals(ut.signature, sigBytes.unsafeBytes())) { throw new SignatureException( "Signature is invalid for username = " + username + ", validUntil " + validUntil); } return ut; } catch (IOException e) { throw new RuntimeException(e); } }
From source file:net.oauth.jsontoken.JsonTokenParser.java
/** * Verifies that the jsonToken has a valid signature and valid standard claims * (iat, exp). Does not need VerifierProviders because verifiers are passed in * directly.//from www . ja v a 2s.c o m * * @param jsonToken the token to verify * @throws SignatureException when the signature is invalid * @throws IllegalStateException when exp or iat are invalid */ public void verify(JsonToken jsonToken, List<Verifier> verifiers) throws SignatureException { if (!signatureIsValid(jsonToken.getTokenString(), verifiers)) { throw new SignatureException("Invalid signature for token: " + jsonToken.getTokenString()); } Instant issuedAt = jsonToken.getIssuedAt(); Instant expiration = jsonToken.getExpiration(); if (issuedAt == null && expiration != null) { issuedAt = new Instant(0); } if (issuedAt != null && expiration == null) { expiration = new Instant(Long.MAX_VALUE); } if (issuedAt != null && expiration != null) { if (issuedAt.isAfter(expiration) || !clock.isCurrentTimeInInterval(issuedAt, expiration)) { throw new IllegalStateException( String.format("Invalid iat and/or exp. iat: %s exp: %s " + "now: %s", jsonToken.getIssuedAt(), jsonToken.getExpiration(), clock.now())); } } if (checkers != null) { for (Checker checker : checkers) { checker.check(jsonToken.getPayloadAsJsonObject()); } } }
From source file:org.panbox.core.keymgmt.JDBCHelperNonRevokeable.java
private void loadSharePaticipants(Connection con, ShareMetaData smd) throws SQLException, SignatureException { smd.shareParticipants = new SharePartList(); // Load Publickeys of participants PreparedStatement s = con.prepareStatement(QUERY_SPL); ResultSet rs = s.executeQuery(); while (rs.next()) { PublicKey key = CryptCore.createPublicKeyFromBytes(rs.getBytes(COL_PUB_KEY)); smd.shareParticipants.add(key, rs.getString(COL_ALIAS)); }/*from w ww . j av a 2 s. c o m*/ rs.close(); // Load and verify signature s = con.prepareStatement(QUERY_SIGNATURE); rs = s.executeQuery(); while (rs.next()) { byte[] signature = rs.getBytes(COL_SIGNATURE); boolean verified = false; try { verified = SignatureHelper.verify(smd.shareParticipants, signature, smd.ownerPubSigKey); smd.shareParticipants.setSignature(signature); } catch (Exception e) { } if (!verified) { throw new SignatureException("ShareParticipantList signature could not be verified!"); } } rs.close(); s.close(); }
From source file:net.oauth.signatures.SignedOAuthTokenParser.java
/** * Parses the provided signed OAuth token, and then verifies it against the provided HTTP method * and audience URI (in addition to checking the signature, and validity period). * @param tokenString the signed OAuth token (in serialized form). * @param method the HTTP method that was used when the token was exercised. * @param uri the URI against which the token was exercised. * @return the signed OAuth token (deserialized) * @throws SignatureException if the signature (or anything else) doesn't check out. *//* w ww.j av a 2s .com*/ public SignedOAuthToken parseToken(String tokenString, String method, String uri) throws SignatureException { JsonTokenParser parser = new JsonTokenParser(clock, locators, new SignedTokenAudienceChecker(uri)); SignedOAuthToken token = new SignedOAuthToken(parser.verifyAndDeserialize(tokenString)); if (!method.equalsIgnoreCase(token.getMethod())) { throw new SignatureException("method does not equal in token (" + token.getMethod() + ")"); } if (nonceChecker != null) { nonceChecker.checkNonce(token.getNonce()); } return token; }
From source file:utils.GenerateAWSSignature.java
/** * Computes RFC 2104-compliant HMAC signature for request parameters * Implements AWS Signature, as per following spec: * * If Signature Version is 0, it signs concatenated Action and Timestamp * * If Signature Version is 1, it performs the following: * * Sorts all parameters (including SignatureVersion and excluding Signature, * the value of which is being created), ignoring case. * * Iterate over the sorted list and append the parameter name (in original case) * and then its value. It will not URL-encode the parameter values before * constructing this string. There are no separators. * * If Signature Version is 2, string to sign is based on following: * * 1. The HTTP Request Method followed by an ASCII newline (%0A) * 2. The HTTP Host header in the form of lowercase host, followed by an ASCII newline. * 3. The URL encoded HTTP absolute path component of the URI * (up to but not including the query string parameters); * if this is empty use a forward '/'. This parameter is followed by an ASCII newline. * 4. The concatenation of all query string components (names and values) * as UTF-8 characters which are URL encoded as per RFC 3986 * (hex characters MUST be uppercase), sorted using lexicographic byte ordering. * Parameter names are separated from their values by the '=' character * (ASCII character 61), even if the value is empty. * Pairs of parameter and values are separated by the '&' character (ASCII code 38). * *//*from w w w . j av a 2 s .c o m*/ private String signParameters(Map<String, String> parameters, String key) throws SignatureException { String signatureVersion = parameters.get("SignatureVersion"); String algorithm = "HmacSHA1"; String stringToSign = null; if ("0".equals(signatureVersion)) { stringToSign = calculateStringToSignV0(parameters); } else if ("1".equals(signatureVersion)) { stringToSign = calculateStringToSignV1(parameters); } else if ("2".equals(signatureVersion)) { //algorithm = config.getSignatureMethod(); algorithm = "HmacSHA256"; parameters.put("SignatureMethod", algorithm); stringToSign = calculateStringToSignV2(parameters); } else { throw new SignatureException("Invalid Signature Version specified"); } System.out.println("Calculated string to sign: " + stringToSign); return sign(stringToSign, key, algorithm); }