Example usage for java.security SignatureException SignatureException

List of usage examples for java.security SignatureException SignatureException

Introduction

In this page you can find the example usage for java.security SignatureException SignatureException.

Prototype

public SignatureException(Throwable cause) 

Source Link

Document

Creates a SignatureException with the specified cause and a detail message of (cause==null ?

Usage

From source file:com.cloud.bridge.util.RestAuth.java

/**
 * Create a signature by the following method:
 *     new String( Base64( SHA1( key, byte array )))
 * //  www. j  a  v  a  2s.co  m
 * @param signIt    - the data to generate a keyed HMAC over
 * @param secretKey - the user's unique key for the HMAC operation
 * @return String   - the recalculated string
 * @throws SignatureException
 */
private String calculateRFC2104HMAC(String signIt, String secretKey) throws SignatureException {
    String result = null;
    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 (InvalidKeyException e) {
        throw new SignatureException("Failed to generate keyed HMAC on REST request because key " + secretKey
                + " is invalid" + e.getMessage());
    } catch (Exception e) {
        throw new SignatureException("Failed to generate keyed HMAC on REST request: " + e.getMessage());
    }
    return result.trim();
}

From source file:org.ejbca.extra.caservice.ExtRACAServiceWorker.java

/**
 * Method used to retrieve which administrator to use.
 * If message is signed then use the signer as admin otherwise use InternalUser
 * @throws SignatureException /*  w w w .  ja v a  2s. c  o  m*/
 * @throws AuthorizationDeniedException 
 */
private Admin getAdmin(SubMessages submessages) throws SignatureException, AuthorizationDeniedException {
    if (submessages.isSigned()) {
        // Check if Signer Cert is revoked
        X509Certificate signerCert = submessages.getSignerCert();
        Admin admin = userAdminSession.getAdmin(signerCert);
        // Check that user have the administrator flag set.
        userAdminSession.checkIfCertificateBelongToUser(admin, signerCert.getSerialNumber(),
                signerCert.getIssuerDN().toString());
        boolean isRevoked = certificateStoreSession.isRevoked(
                CertTools.stringToBCDNString(signerCert.getIssuerDN().toString()),
                signerCert.getSerialNumber());
        if (isRevoked) {
            throw new SignatureException("Error Signer certificate doesn't exist or is revoked.");
        }
        return admin;
    }
    return internalUser;
}

From source file:com.telesign.util.TeleSignRequest.java

/**
 * Creates the Signature component for the Authorization header field.
 * Uses your Secret Key to encode the stringToSign.
 * This is a <em>helper method</em>, used internally by the {@link TeleSignRequest#executeRequest()} method.
 *
 * @param data//  w w  w  . j  av a  2s  . c om
 *         [Required] The stringToSign.
 * @param key
 *         [Required] Your TeleSign API Key. Also known as your Secret
 *         Key, and your Shared Cryptographic Key. It s a bese64-encoded
 *         string value.
 * @return A String containing the Base64-encoded hash-based message
 *       authentication code.
 * @throws java.security.SignatureException
 *          Failed to generate HMAC. IllegalArgumentException - if
 *          algorithm is null or key is null or empty.
 */
private String encode(String data, String key) throws java.security.SignatureException {

    String result;

    byte[] decoded_key = Base64.decodeBase64(key);

    try {
        // Get an hmac_sha key from the raw key bytes.
        SecretKeySpec signingKey = new SecretKeySpec(decoded_key, auth.value());

        // Get an hmac_sha Mac instance, and initialize it with the signing key.
        Mac mac = Mac.getInstance(auth.value());
        mac.init(signingKey);

        // Compute the HMAC on input data bytes.
        byte[] rawHmac = mac.doFinal(data.getBytes());

        // Base64-encode the HMAC.
        result = new String(Base64.encodeBase64(rawHmac));

    } catch (Exception e) {

        throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
    }

    return result;
}

From source file:API.amazon.mws.orders.MarketplaceWebServiceOrdersClient.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).
 *
 *//*w ww.  ja va  2s. 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();
        parameters.put("SignatureMethod", algorithm);
        stringToSign = calculateStringToSignV2(parameters);
    } else {
        throw new SignatureException("Invalid Signature Version specified");
    }
    log.debug("Calculated string to sign: " + stringToSign);
    return sign(stringToSign, key, algorithm);
}

From source file:org.dasein.cloud.virtustream.VirtustreamMethod.java

private byte[] calculateHmac(String data, String key) throws SignatureException {
    try {//w  ww  .j a  va 2  s  .  co m
        SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), "HmacSHA256");
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(signingKey);

        return mac.doFinal(data.getBytes());
    } catch (Exception e) {
        throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
    }
}

From source file:org.wso2.carbon.identity.application.common.util.IdentityApplicationManagementUtil.java

/**
 * @param key//from www .  ja va  2 s  . c o m
 * @param value
 * @return
 * @throws SignatureException
 */
public static String calculateHmacSha1(String key, String value) throws SignatureException {
    String result;
    try {
        SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(signingKey);
        byte[] rawHmac = mac.doFinal(value.getBytes());
        result = Base64Utils.encode(rawHmac);
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.debug("Failed to create the HMAC Signature", e);
        }
        throw new SignatureException("Failed to calculate HMAC : " + e.getMessage());
    }
    return result;
}

From source file:gpps.service.impl.ThirdPaySupportServiceImpl.java

public void checkRollBack(Map<String, String> params, String[] signStrs)
        throws ResultCodeException, SignatureException {
    String resultCode = params.get("ResultCode");
    if (StringUtil.isEmpty(resultCode) || !resultCode.equals("88"))
        throw new ResultCodeException(resultCode, params.get("Message"));
    StringBuilder sBuilder = new StringBuilder();
    for (String str : signStrs) {
        sBuilder.append(StringUtil.strFormat(params.get(str)));
    }//from w w w .j a v a2  s. c o m
    RsaHelper rsa = RsaHelper.getInstance();
    String sign = rsa.signData(sBuilder.toString(), innerThirdPaySupportService.getPrivateKey());
    if (!sign.replaceAll("\r", "").equals(params.get("SignInfo").replaceAll("\r", "")))
        throw new SignatureException("???");
}

From source file:org.cesecore.certificates.ca.X509CA.java

/**
 * Generate a CRL or a deltaCRL//ww  w .j  a v  a2  s.  c o  m
 * 
 * @param certs
 *            list of revoked certificates
 * @param crlnumber
 *            CRLNumber for this CRL
 * @param isDeltaCRL
 *            true if we should generate a DeltaCRL
 * @param basecrlnumber
 *            caseCRLNumber for a delta CRL, use 0 for full CRLs
 * @param certProfile
 *            certificate profile for CRL Distribution point in the CRL, or null
 * @return CRL
 * @throws CryptoTokenOfflineException
 * @throws IllegalCryptoTokenException
 * @throws IOException
 * @throws SignatureException
 * @throws NoSuchProviderException
 * @throws InvalidKeyException
 * @throws CRLException
 * @throws NoSuchAlgorithmException
 */
private X509CRLHolder generateCRL(CryptoToken cryptoToken, Collection<RevokedCertInfo> certs, long crlPeriod,
        int crlnumber, boolean isDeltaCRL, int basecrlnumber)
        throws CryptoTokenOfflineException, IllegalCryptoTokenException, IOException, SignatureException,
        NoSuchProviderException, InvalidKeyException, CRLException, NoSuchAlgorithmException {
    final String sigAlg = getCAInfo().getCAToken().getSignatureAlgorithm();

    if (log.isDebugEnabled()) {
        log.debug("generateCRL(" + certs.size() + ", " + crlPeriod + ", " + crlnumber + ", " + isDeltaCRL + ", "
                + basecrlnumber);
    }

    // Make DNs
    final X509Certificate cacert = (X509Certificate) getCACertificate();
    final X500Name issuer;
    if (cacert == null) {
        // This is an initial root CA, since no CA-certificate exists
        // (I don't think we can ever get here!!!)
        final X500NameStyle nameStyle;
        if (getUsePrintableStringSubjectDN()) {
            nameStyle = PrintableStringNameStyle.INSTANCE;
        } else {
            nameStyle = CeSecoreNameStyle.INSTANCE;
        }
        issuer = CertTools.stringToBcX500Name(getSubjectDN(), nameStyle, getUseLdapDNOrder());
    } else {
        issuer = X500Name.getInstance(cacert.getSubjectX500Principal().getEncoded());
    }
    final Date thisUpdate = new Date();
    final Date nextUpdate = new Date();
    nextUpdate.setTime(nextUpdate.getTime() + crlPeriod);
    final X509v2CRLBuilder crlgen = new X509v2CRLBuilder(issuer, thisUpdate);
    crlgen.setNextUpdate(nextUpdate);
    if (certs != null) {
        if (log.isDebugEnabled()) {
            log.debug("Adding " + certs.size() + " revoked certificates to CRL. Free memory="
                    + Runtime.getRuntime().freeMemory());
        }
        final Iterator<RevokedCertInfo> it = certs.iterator();
        while (it.hasNext()) {
            final RevokedCertInfo certinfo = (RevokedCertInfo) it.next();
            crlgen.addCRLEntry(certinfo.getUserCertificate(), certinfo.getRevocationDate(),
                    certinfo.getReason());
        }
        if (log.isDebugEnabled()) {
            log.debug("Finished adding " + certs.size() + " revoked certificates to CRL. Free memory="
                    + Runtime.getRuntime().freeMemory());
        }
    }

    // Authority key identifier
    if (getUseAuthorityKeyIdentifier() == true) {
        byte[] caSkid = (cacert != null ? CertTools.getSubjectKeyId(cacert) : null);
        if (caSkid != null) {
            // Use subject key id from CA certificate
            AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(caSkid);
            crlgen.addExtension(Extension.authorityKeyIdentifier, getAuthorityKeyIdentifierCritical(), aki);
        } else {
            // Generate from SHA1 of public key
            ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(cryptoToken
                    .getPublicKey(getCAToken().getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CRLSIGN))
                    .getEncoded()));
            try {
                SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo(
                        (ASN1Sequence) asn1InputStream.readObject());
                AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki);
                crlgen.addExtension(Extension.authorityKeyIdentifier, getAuthorityKeyIdentifierCritical(), aki);
            } finally {
                asn1InputStream.close();
            }
        }
    }

    // Authority Information Access  
    final ASN1EncodableVector accessList = new ASN1EncodableVector();
    if (getAuthorityInformationAccess() != null) {
        for (String url : getAuthorityInformationAccess()) {
            if (StringUtils.isNotEmpty(url)) {
                GeneralName accessLocation = new GeneralName(GeneralName.uniformResourceIdentifier,
                        new DERIA5String(url));
                accessList.add(new AccessDescription(AccessDescription.id_ad_caIssuers, accessLocation));
            }
        }
    }
    if (accessList.size() > 0) {
        AuthorityInformationAccess authorityInformationAccess = AuthorityInformationAccess
                .getInstance(new DERSequence(accessList));
        // "This CRL extension MUST NOT be marked critical." according to rfc4325
        crlgen.addExtension(Extension.authorityInfoAccess, false, authorityInformationAccess);
    }

    // CRLNumber extension
    if (getUseCRLNumber() == true) {
        CRLNumber crlnum = new CRLNumber(BigInteger.valueOf(crlnumber));
        crlgen.addExtension(Extension.cRLNumber, this.getCRLNumberCritical(), crlnum);
    }

    if (isDeltaCRL) {
        // DeltaCRLIndicator extension
        CRLNumber basecrlnum = new CRLNumber(BigInteger.valueOf(basecrlnumber));
        crlgen.addExtension(Extension.deltaCRLIndicator, true, basecrlnum);
    }
    // CRL Distribution point URI and Freshest CRL DP
    if (getUseCrlDistributionPointOnCrl()) {
        String crldistpoint = getDefaultCRLDistPoint();
        List<DistributionPoint> distpoints = generateDistributionPoints(crldistpoint);

        if (distpoints.size() > 0) {
            IssuingDistributionPoint idp = new IssuingDistributionPoint(
                    distpoints.get(0).getDistributionPoint(), false, false, null, false, false);

            // According to the RFC, IDP must be a critical extension.
            // Nonetheless, at the moment, Mozilla is not able to correctly
            // handle the IDP extension and discards the CRL if it is critical.
            crlgen.addExtension(Extension.issuingDistributionPoint, getCrlDistributionPointOnCrlCritical(),
                    idp);
        }

        if (!isDeltaCRL) {
            String crlFreshestDP = getCADefinedFreshestCRL();
            List<DistributionPoint> freshestDistPoints = generateDistributionPoints(crlFreshestDP);
            if (freshestDistPoints.size() > 0) {
                CRLDistPoint ext = new CRLDistPoint((DistributionPoint[]) freshestDistPoints
                        .toArray(new DistributionPoint[freshestDistPoints.size()]));

                // According to the RFC, the Freshest CRL extension on a
                // CRL must not be marked as critical. Therefore it is
                // hardcoded as not critical and is independent of
                // getCrlDistributionPointOnCrlCritical().
                crlgen.addExtension(Extension.freshestCRL, false, ext);
            }

        }
    }

    final X509CRLHolder crl;
    if (log.isDebugEnabled()) {
        log.debug("Signing CRL. Free memory=" + Runtime.getRuntime().freeMemory());
    }
    final String alias = getCAToken().getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CRLSIGN);
    try {
        final ContentSigner signer = new BufferingContentSigner(new JcaContentSignerBuilder(sigAlg)
                .setProvider(cryptoToken.getSignProviderName()).build(cryptoToken.getPrivateKey(alias)), 20480);
        crl = crlgen.build(signer);
    } catch (OperatorCreationException e) {
        // Very fatal error
        throw new RuntimeException("Can not create Jca content signer: ", e);
    }
    if (log.isDebugEnabled()) {
        log.debug("Finished signing CRL. Free memory=" + Runtime.getRuntime().freeMemory());
    }

    // Verify using the CA certificate before returning
    // If we can not verify the issued CRL using the CA certificate we don't want to issue this CRL
    // because something is wrong...
    final PublicKey verifyKey;
    if (cacert != null) {
        verifyKey = cacert.getPublicKey();
        if (log.isTraceEnabled()) {
            log.trace("Got the verify key from the CA certificate.");
        }
    } else {
        verifyKey = cryptoToken.getPublicKey(alias);
        if (log.isTraceEnabled()) {
            log.trace("Got the verify key from the CA token.");
        }
    }
    try {
        final ContentVerifierProvider verifier = new JcaContentVerifierProviderBuilder().build(verifyKey);
        if (!crl.isSignatureValid(verifier)) {
            throw new SignatureException("Error verifying CRL to be returned.");
        }
    } catch (OperatorCreationException e) {
        // Very fatal error
        throw new RuntimeException("Can not create Jca content signer: ", e);
    } catch (CertException e) {
        throw new SignatureException(e.getMessage(), e);
    }
    if (log.isDebugEnabled()) {
        log.debug("Returning CRL. Free memory=" + Runtime.getRuntime().freeMemory());
    }
    return crl;
}

From source file:API.amazon.mws.feeds.service.MarketplaceWebServiceClient.java

/**
 * Computes RFC 2104-compliant HMAC signature for request parameters
 * Implements AWS Signature, as per following spec:
 *
 * 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. jav  a 2 s  .  c  om*/
private String signParameters(Map<String, String> parameters, String key) throws SignatureException {

    String signatureVersion = parameters.get("SignatureVersion");
    String algorithm = "HmacSHA1";
    String stringToSign = null;
    if ("2".equals(signatureVersion)) {
        algorithm = config.getSignatureMethod();
        parameters.put("SignatureMethod", algorithm);
        stringToSign = calculateStringToSignV2(parameters);
    } else {
        throw new SignatureException("Invalid Signature Version specified");
    }
    log.debug("Calculated string to sign: " + stringToSign);
    return sign(stringToSign, key, algorithm);
}