Example usage for java.lang SecurityException SecurityException

List of usage examples for java.lang SecurityException SecurityException

Introduction

In this page you can find the example usage for java.lang SecurityException SecurityException.

Prototype

public SecurityException(String message, Throwable cause) 

Source Link

Document

Creates a SecurityException with the specified detail message and cause.

Usage

From source file:org.apache.hawq.pxf.service.utilities.SecuredHDFS.java

/**
 * The function will get the token information from parameters and call
 * SecuredHDFS to verify the token./*from w  ww.  ja v  a2  s  .c  o m*/
 *
 * All token properties will be deserialized from string to a Token object
 *
 * @param protData input parameters
 * @param context servlet context which contains the NN address
 *
 * @throws SecurityException Thrown when authentication fails
 */
public static void verifyToken(ProtocolData protData, ServletContext context) {
    try {
        if (UserGroupInformation.isSecurityEnabled()) {
            Token<DelegationTokenIdentifier> token = new Token<DelegationTokenIdentifier>();
            String tokenString = protData.getToken();
            token.decodeFromUrlString(tokenString);

            verifyToken(token.getIdentifier(), token.getPassword(), token.getKind(), token.getService(),
                    context);
        }
    } catch (IOException e) {
        throw new SecurityException("Failed to verify delegation token " + e, e);
    }
}

From source file:edu.internet2.middleware.openid.security.SecurityUtils.java

/**
 * Sign the OpenID message using the specified assertion. All available message parameters and namespace
 * declarations, including those provided by message extensions, will be used to calculate the signature. This
 * method will populate both the signature value and list of signed fields for the message. Once a message has been
 * signed, it should not be modified any further.
 * // w  ww  . j a v a2 s .  c  om
 * @param message message to sign
 * @param association association used to generate signature
 * @throws SecurityException if unable to sign the message
 */
public static void signMessage(SignableMessage message, Association association) throws SecurityException {
    log.info("signing message with association: {}", association.getHandle());

    ParameterMap messageParameters;
    try {
        MessageMarshaller marshaller = Configuration.getMessageMarshallers().getMarshaller(message);
        messageParameters = marshaller.marshall(message);
    } catch (MarshallingException e) {
        log.error("Unable to sign message - " + e.getMessage());
        throw new SecurityException("Unable to sign message", e);
    }

    List<QName> signedParameters = buildSignedParameters(messageParameters);
    String signatureData = buildSignatureData(messageParameters, signedParameters);
    String signature = calculateSignature(association, signatureData);

    message.getSignedFields().clear();
    message.getSignedFields().addAll(signedParameters);
    message.setSignature(signature);
}

From source file:com.easarrive.aws.plugins.common.util.SNSUtil.java

public static boolean isMessageSignatureValid(SNSMessage msg) {
    try {//from ww w  . ja  va2 s  .co m
        URL url = new URL(msg.getSigningCertURL());
        InputStream inStream = url.openStream();
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream);
        inStream.close();

        Signature sig = Signature.getInstance("SHA1withRSA");
        sig.initVerify(cert.getPublicKey());
        sig.update(getMessageBytesToSign(msg));
        return sig.verify(Base64.decodeBase64(msg.getSignature()));
    } catch (Exception e) {
        throw new SecurityException("Verify method failed.", e);
    }
}

From source file:org.apache.hawq.pxf.service.utilities.SecuredHDFS.java

/**
 * The function will verify the token with NameNode if available and will
 * create a UserGroupInformation./* w  w  w. j av  a 2 s.  com*/
 *
 * Code in this function is copied from JspHelper.getTokenUGI
 *
 * @param identifier Delegation token identifier
 * @param password Delegation token password
 * @param kind the kind of token
 * @param service the service for this token
 * @param servletContext Jetty servlet context which contains the NN address
 *
 * @throws SecurityException Thrown when authentication fails
 */
private static void verifyToken(byte[] identifier, byte[] password, Text kind, Text service,
        ServletContext servletContext) {
    try {
        Token<DelegationTokenIdentifier> token = new Token<DelegationTokenIdentifier>(identifier, password,
                kind, service);

        ByteArrayInputStream buf = new ByteArrayInputStream(token.getIdentifier());
        DataInputStream in = new DataInputStream(buf);
        DelegationTokenIdentifier id = new DelegationTokenIdentifier();
        id.readFields(in);

        final NameNode nn = NameNodeHttpServer.getNameNodeFromContext(servletContext);
        if (nn != null) {
            nn.getNamesystem().verifyToken(id, token.getPassword());
        }

        UserGroupInformation userGroupInformation = id.getUser();
        userGroupInformation.addToken(token);
        LOG.debug("user " + userGroupInformation.getUserName() + " (" + userGroupInformation.getShortUserName()
                + ") authenticated");

        // re-login if necessary
        userGroupInformation.checkTGTAndReloginFromKeytab();
    } catch (IOException e) {
        throw new SecurityException("Failed to verify delegation token " + e, e);
    }
}

From source file:edu.internet2.middleware.openid.security.SecurityUtils.java

/**
 * Verify that the signature on an OpenID message is valid using the specified association.
 * //  w w  w  .j  a  v  a 2s .c  o m
 * @param message message to verify signature for
 * @param association association used to verify signature
 * @return true if the signature is valid, false if it is not
 * @throws SecurityException if unable to validate the signature
 */
public static boolean signatureIsValid(SignableMessage message, Association association)
        throws SecurityException {
    log.info("validating message signature");

    ParameterMap messageParameters;
    try {
        MessageMarshaller marshaller = Configuration.getMessageMarshallers().getMarshaller(message);
        messageParameters = marshaller.marshall(message);
    } catch (MarshallingException e) {
        log.error("Unable verify message signature - " + e.getMessage());
        throw new SecurityException("Unable to verify message signature", e);
    }

    String signatureData = buildSignatureData(messageParameters, message.getSignedFields());
    String signature = calculateSignature(association, signatureData);
    return signature.equals(message.getSignature());
}

From source file:be.fedict.commons.eid.consumer.BeIDIntegrity.java

/**
 * Gives back a parsed identity file after integrity verification including
 * the eID photo./*w w w. j  a  va  2s . com*/
 * 
 * @param identityFile
 * @param identitySignatureFile
 * @param photo
 * @param rrnCertificate
 * @return
 * @throws NoSuchAlgorithmException
 */
public Identity getVerifiedIdentity(final byte[] identityFile, final byte[] identitySignatureFile,
        final byte[] photo, final X509Certificate rrnCertificate) throws NoSuchAlgorithmException {
    final PublicKey publicKey = rrnCertificate.getPublicKey();
    boolean result;
    try {
        result = verifySignature(rrnCertificate.getSigAlgName(), identitySignatureFile, publicKey,
                identityFile);
    } catch (final Exception ex) {
        throw new SecurityException("identity signature verification error: " + ex.getMessage(), ex);
    }
    if (false == result) {
        throw new SecurityException("signature integrity error");
    }
    final Identity identity = TlvParser.parse(identityFile, Identity.class);
    if (null != photo) {
        final byte[] expectedPhotoDigest = identity.getPhotoDigest();
        final byte[] actualPhotoDigest = digest(getDigestAlgo(expectedPhotoDigest.length), photo);
        if (false == Arrays.equals(expectedPhotoDigest, actualPhotoDigest)) {
            throw new SecurityException("photo digest mismatch");
        }
    }
    return identity;
}

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/*  ww  w .j a  va  2  s .co  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:com.amalto.workbench.utils.SSLContextProvider.java

public synchronized static void buildContext(String algorithm, String keypath, String keypass, String keytype,
        String trustpath, String trustpass, String trusttype) {
    try {/*from   www. ja va2s.  c  o  m*/
        KeyManager[] kms = buildKeyManagers(keypath, keypass, keytype);
        TrustManager[] tms = buildTrustManagers(trustpath, trustpass, trusttype);
        SSLContext sslcontext = SSLContext.getInstance(algorithm);
        sslcontext.init(kms, tms, null);
        context = sslcontext;
    } catch (Exception e) {
        throw new SecurityException(e.getMessage(), e);
    }
}

From source file:be.fedict.trust.client.WSSecurityClientHandler.java

/**
 * Handles the inbound SOAP message. If a WS-Security header is present, it
 * will be validated. If a server certificate was specified, it will be
 * checked against the {@link X509Certificate} in the WS-Security header.
 *///from  w w  w  .  j av a  2  s  .c  o m
private boolean handleInboundDocument(SOAPPart document, SOAPMessageContext soapMessageContext) {
    WSSecurityEngine securityEngine = new WSSecurityEngine();
    WSSConfig wssConfig = WSSConfig.getNewInstance();
    securityEngine.setWssConfig(wssConfig);

    List<WSSecurityEngineResult> wsSecurityEngineResults;
    try {
        Crypto crypto = new ServerCrypto();
        wsSecurityEngineResults = securityEngine.processSecurityHeader(document, null, null, crypto);
    } catch (WSSecurityException e) {
        LOG.debug("WS-Security error: " + e.getMessage(), e);
        throw new SecurityException("WS-Security error: " + e.getMessage(), e);
    }
    if (null == wsSecurityEngineResults) {
        LOG.debug("No WS-Security header to validate");
        return true;
    }
    LOG.debug("WS-Security header validation");

    // WS-Security timestamp validation
    WSSecurityEngineResult timeStampActionResult = WSSecurityUtil.fetchActionResult(wsSecurityEngineResults,
            WSConstants.TS);
    if (null == timeStampActionResult) {
        throw new SecurityException("no WS-Security timestamp result");
    }
    Timestamp receivedTimestamp = (Timestamp) timeStampActionResult.get(WSSecurityEngineResult.TAG_TIMESTAMP);
    if (null == receivedTimestamp) {
        throw new SecurityException(ERROR_TIMESTAMP_MISSING);
    }

    // WS-Security signature
    WSSecurityEngineResult signActionResult = WSSecurityUtil.fetchActionResult(wsSecurityEngineResults,
            WSConstants.SIGN);
    if (null == signActionResult) {
        throw new SecurityException("missing WS-Security signature");
    }
    X509Certificate signingCertificate = (X509Certificate) signActionResult
            .get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);

    /*
     * Validate certificate
     */
    if (null == signingCertificate) {
        throw new SecurityException(ERROR_CERTIFICATE_MISSING);
    }
    if (null != this.serverCertificate && !serverCertificate.equals(signingCertificate)) {
        throw new SecurityException(ERROR_CERTIFICATE_MISMATCH);
    }

    return true;
}

From source file:be.fedict.commons.eid.consumer.BeIDIntegrity.java

/**
 * Gives back a parsed address file after integrity verification.
 * //  ww  w.j  a  va  2 s .  c om
 * @param addressFile
 * @param identitySignatureFile
 * @param addressSignatureFile
 * @param rrnCertificate
 * @return
 */
public Address getVerifiedAddress(final byte[] addressFile, final byte[] identitySignatureFile,
        final byte[] addressSignatureFile, final X509Certificate rrnCertificate) {
    final byte[] trimmedAddressFile = trimRight(addressFile);
    final PublicKey publicKey = rrnCertificate.getPublicKey();
    boolean result;
    try {
        result = verifySignature(rrnCertificate.getSigAlgName(), addressSignatureFile, publicKey,
                trimmedAddressFile, identitySignatureFile);
    } catch (final Exception ex) {
        throw new SecurityException("address signature verification error: " + ex.getMessage(), ex);
    }
    if (false == result) {
        throw new SecurityException("address integrity error");
    }
    final Address address = TlvParser.parse(addressFile, Address.class);
    return address;

}