Example usage for java.security GeneralSecurityException toString

List of usage examples for java.security GeneralSecurityException toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns a short description of this throwable.

Usage

From source file:com.streamsets.lib.security.http.SignedSSOTokenParser.java

protected boolean verifySignature(String data, String signatureB64) {
    boolean valid = false;
    DataSignature.Verifier[] currentVerifiers = this.verifiers;
    if (currentVerifiers.length > 0) {
        for (int i = 0; !valid && i < currentVerifiers.length; i++) {
            try {
                valid = currentVerifiers[i].verify(data.getBytes(), Base64.decodeBase64(signatureB64));
            } catch (GeneralSecurityException ex) {
                getLog().error("Error verifying signature: {}", ex.toString(), ex);
            }// w w w . ja v  a2 s.  c om
        }
        if (!valid) {
            getLog().warn("Invalid signature for '{}'", data);
        }
    } else {
        getLog().error("There are no public keys, cannot verify signature");
    }
    return valid;
}

From source file:com.streamsets.lib.security.http.SignedSSOTokenParser.java

protected synchronized void setPublicKey(String encodedKey) {
    if (encodedKey != null) {
        if (!encodedKey.equals(lastEncodedKey)) {
            lastEncodedKey = encodedKey;
            try {
                PublicKey publicKey = DataSignature.get().decodePublicKey(encodedKey);
                DataSignature.Verifier newVerifier = DataSignature.get().getVerifier(publicKey);
                int size = (verifiers.length < 2) ? verifiers.length + 1 : 2;
                getLog().debug("Got new signature, rotating verifiers");
                DataSignature.Verifier[] newVerifiers = new DataSignature.Verifier[size];
                newVerifiers[0] = newVerifier;
                if (size == 2) {
                    newVerifiers[1] = verifiers[0];
                }//from w ww  .ja  va  2s . c o  m
                verifiers = newVerifiers;
            } catch (GeneralSecurityException ex) {
                getLog().error("Error setting public key, disabling verifier: {}", ex.toString(), ex);
                lastEncodedKey = null;
                verifiers = new DataSignature.Verifier[0];
            }
        } else {
            getLog().debug("Got same signature, ignoring");
        }
    } else {
        getLog().debug("Parser disabled, public key set to NULL");
        lastEncodedKey = null;
        verifiers = new DataSignature.Verifier[0];
    }
}

From source file:cn.com.mozilla.sync.utils.HttpsTransport.java

public HttpsTransport() {
    // Create SSL socket factory
    if (ALLOW_INVALID_CERTS) {

        try {/*from w w  w.  jav a  2 s  .c  om*/
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);
            mSslSocketFactory = new EasySSLSocketFactory(trustStore);
        } catch (GeneralSecurityException e) {
            Log.w("Firefoxmini", e.toString());
        } catch (IOException e) {
            Log.w("Firefoxmini", e.toString());
        }
    }
    if (mSslSocketFactory == null) {
        mSslSocketFactory = SSLSocketFactory.getSocketFactory();
    }

    // Create ClientConnectionManager
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("https", mSslSocketFactory, HTTPS_PORT_DEFAULT));
    mClientConMgr = new SingleClientConnManager(sHttpParams, schemeRegistry);
}

From source file:com.netscape.cms.logging.LogFile.java

/**
 * This method actually does the logging, and is not overridden
 * by subclasses, so you can call it and know that it will do exactly
 * what you see below.//from   w w w  .j av  a  2s  .  c  om
 */
private synchronized void doLog(ILogEvent event, boolean noFlush) throws ELogException {

    String entry = logEvt2String(event);

    if (mLogWriter == null) {
        String[] params = { mFileName, entry };

        if (mLogSigning) {
            ConsoleError.send(new SystemEvent(CMS.getUserMessage("CMS_LOG_LOGFILE_CLOSED", params)));
            // Failed to write to audit log, shut down CMS
            shutdownCMS();
        }
        throw new ELogException(CMS.getUserMessage("CMS_LOG_LOGFILE_CLOSED", params));
    } else {
        try {
            mLogWriter.write(entry, 0/*offset*/, entry.length());

            if (mLogSigning == true) {
                if (mSignature != null) {
                    // include newline for calculating MAC
                    mSignature.update(entry.getBytes("UTF-8"));
                } else {
                    CMS.debug("LogFile: mSignature is not yet ready... null in log()");
                }
            }
            if (mTrace) {
                CharArrayWriter cw = new CharArrayWriter(200);
                PrintWriter pw = new PrintWriter(cw);
                Exception e = new Exception();
                e.printStackTrace(pw);
                char[] c = cw.toCharArray();
                cw.close();
                pw.close();

                CharArrayReader cr = new CharArrayReader(c);
                LineNumberReader lr = new LineNumberReader(cr);

                String text = null;
                String method = null;
                String fileAndLine = null;
                if (lr.ready()) {
                    text = lr.readLine();
                    do {
                        text = lr.readLine();
                    } while (text.indexOf("logging") != -1);
                    int p = text.indexOf("(");
                    fileAndLine = text.substring(p);

                    String classandmethod = text.substring(0, p);
                    int q = classandmethod.lastIndexOf(".");
                    method = classandmethod.substring(q + 1);
                    mLogWriter.write(fileAndLine, 0/*offset*/, fileAndLine.length());
                    mLogWriter.write(" ", 0/*offset*/, " ".length());
                    mLogWriter.write(method, 0/*offset*/, method.length());
                }
            }
            mLogWriter.newLine();

            if (mLogSigning == true) {
                if (mSignature != null) {
                    mSignature.update(LINE_SEP_BYTE);
                } else {
                    CMS.debug("LogFile: mSignature is null in log() 2");
                }
            }
        } catch (IOException e) {
            ConsoleError.send(new SystemEvent(
                    CMS.getUserMessage("CMS_LOG_WRITE_FAILED", mFileName, entry, e.toString())));
            if (mLogSigning) {
                // Failed to write to audit log, shut down CMS
                e.printStackTrace();
                shutdownCMS();
            }
        } catch (IllegalStateException e) {
            CMS.debug("LogFile: exception thrown in log(): " + e.toString());
            ConsoleError
                    .send(new SignedAuditEvent(CMS.getLogMessage(LOG_SIGNED_AUDIT_EXCEPTION, e.toString())));
        } catch (GeneralSecurityException gse) {
            // DJN: handle error
            CMS.debug("LogFile: exception thrown in log(): " + gse.toString());
            gse.printStackTrace();
            ConsoleError
                    .send(new SignedAuditEvent(CMS.getLogMessage(LOG_SIGNED_AUDIT_EXCEPTION, gse.toString())));
        } catch (Exception ee) { // Make darn sure we got everything
            ConsoleError
                    .send(new SignedAuditEvent(CMS.getLogMessage(LOG_SIGNED_AUDIT_EXCEPTION, ee.toString())));
            if (mLogSigning) {
                // Failed to write to audit log, shut down CMS
                ee.printStackTrace();
                shutdownCMS();
            }

        }

        // XXX
        // Although length will be in Unicode dual-bytes, the PrintWriter
        // will only print out 1 byte per character.  I suppose this could
        // be dependent on the encoding of your log file, but it ain't that
        // smart yet.  Also, add one for the newline. (hmm, on NT, CR+LF)
        int nBytes = entry.length() + 1;

        mBytesWritten += nBytes;
        mBytesUnflushed += nBytes;

        if (mBufferSize > 0 && mBytesUnflushed > mBufferSize && !noFlush) {
            flush();
        }
    }
}

From source file:com.netscape.cms.logging.LogFile.java

/**
 * Open the log file. This creates the buffered FileWriter
 *
 *//*  ww w .  ja v a 2  s .  com*/
protected synchronized void open() throws IOException {
    RandomAccessFile out;

    try {
        out = new RandomAccessFile(mFile, "rw");
        out.seek(out.length());
        //XXX int or long?
        mBytesWritten = (int) out.length();
        if (!Utils.isNT()) {
            try {
                Utils.exec("chmod 00640 " + mFile.getCanonicalPath());
            } catch (IOException e) {
                CMS.debug("Unable to change file permissions on " + mFile.toString());
            }
        }
        mLogWriter = new BufferedWriter(new FileWriter(out.getFD()), mBufferSize);

        // The first time we open, mSignature will not have been
        // initialized yet. That's ok, we will push our first signature
        // in setupSigning().
        if (mLogSigning && (mSignature != null)) {
            try {
                pushSignature();
            } catch (ELogException le) {
                ConsoleError.send(new SystemEvent(CMS.getUserMessage("CMS_LOG_ILLEGALARGUMENT", mFileName)));
            }
        }
    } catch (IllegalArgumentException iae) {
        ConsoleError.send(new SystemEvent(CMS.getUserMessage("CMS_LOG_ILLEGALARGUMENT", mFileName)));
    } catch (GeneralSecurityException gse) {
        // error with signed audit log, shutdown CMS
        ConsoleError
                .send(new SystemEvent(CMS.getUserMessage("CMS_LOG_OPEN_FAILED", mFileName, gse.toString())));
        gse.printStackTrace();
        shutdownCMS();
    }

    mBytesUnflushed = 0;
}

From source file:com.netscape.cms.logging.LogFile.java

/**
 * Flush the log file. Also update the MAC for hash protected logs
 *
 *///from  w w w. j  a  va2  s.  c  o  m
public synchronized void flush() {
    try {
        if (mLogSigning) {
            try {
                pushSignature();
            } catch (ELogException le) {
                ConsoleError.send(new SystemEvent(
                        CMS.getUserMessage("CMS_LOG_FLUSH_LOG_FAILED", mFileName, le.toString())));
                le.printStackTrace();
                shutdownCMS();
            }
        }

        if (mLogWriter != null) {
            mLogWriter.flush();
        }
    } catch (IOException e) {
        ConsoleError
                .send(new SystemEvent(CMS.getUserMessage("CMS_LOG_FLUSH_LOG_FAILED", mFileName, e.toString())));
        if (mLogSigning) {
            //error in writing to signed audit log, shut down CMS
            e.printStackTrace();
            shutdownCMS();
        }
    } catch (GeneralSecurityException gse) {
        // error with signed audit log, shutdown CMS
        ConsoleError.send(
                new SystemEvent(CMS.getUserMessage("CMS_LOG_FLUSH_LOG_FAILED", mFileName, gse.toString())));
        gse.printStackTrace();
        shutdownCMS();
    } catch (Exception ee) {
        ConsoleError.send(
                new SystemEvent(CMS.getUserMessage("CMS_LOG_FLUSH_LOG_FAILED", mFileName, ee.toString())));
        if (mLogSigning) {
            ee.printStackTrace();
            shutdownCMS();
        }
    }

    mBytesUnflushed = 0;
}

From source file:org.lsc.utils.security.SymmetricEncryption.java

/**
 * This main allow user to generate random key file.
 * @param argv/*from w  w  w .j a v a2  s  . co  m*/
 */
public static void main(String argv[]) {
    try {
        Options options = new Options();
        options.addOption("f", "cfg", true, "Specify configuration directory");
        CommandLine cmdLine = new GnuParser().parse(options, argv);

        if (cmdLine.getOptions().length > 0 && cmdLine.hasOption("f")) {
            // if a configuration directory was set on command line, use it to set up Configuration
            Configuration.setUp(cmdLine.getOptionValue("f"), false);
        } else {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("lsc", options);
            System.exit(1);
        }
    } catch (ParseException e) {
        StringBuilder sbf = new StringBuilder();
        for (String arg : argv) {
            sbf.append(arg).append(" ");
        }

        LOGGER.error("Unable to parse options : {}({})", sbf.toString(), e);
        System.exit(1);
    } catch (LscException e) {
        LOGGER.error("Something goes wrong while loading configuration: " + e.toString(), e);
        System.exit(2);
    }

    try {
        if (LscConfiguration.getSecurity() == null) {
            throw new RuntimeException("lsc>security node of the LSC configuration cannot be null !");
        } else if (LscConfiguration.getSecurity().getEncryption() == null) {
            throw new RuntimeException(
                    "lsc>security>encryption node of the LSC configuration cannot be null !");
        }
        SymmetricEncryption se = new SymmetricEncryption(LscConfiguration.getSecurity().getEncryption());
        if (se.generateDefaultRandomKeyFile()) {
            LOGGER.info(
                    "Key generated: {}. Do not forget to check the lsc>security>encryption>keyfile node value in your configuration file !",
                    se.keyPath);
        }
    } catch (GeneralSecurityException ex) {
        LOGGER.debug(ex.toString(), ex);
    }
}

From source file:servlets.module.challenge.BrokenCryptoHomeMade.java

/**
 * Specifically decrypts encrypted user names
 * @param encyptedUserName Encrypted user name
 * @return Decrypted User name//from  www .j a  va  2 s . c  o  m
 */
public static String decryptUserName(String encyptedUserName) {
    String decryptedUserName = new String();
    try {
        decryptedUserName = decrypt(userNameKey, encyptedUserName);
        log.debug("Decrypted user-name to: " + decryptedUserName);
    } catch (GeneralSecurityException e) {
        log.error("Could not decrypt user name: " + e.toString());
    }
    return decryptedUserName;
}

From source file:utils.Hash.java

/**
 * Specifically decrypts encrypted user names
 * @param encyptedUserName Encrypted user name
 * @return Decrypted User name//  w  w w  .  j  a va2s.  co  m
 */
public static String decryptUserName(String encyptedUserName) {
    String decryptedUserName = new String();
    try {
        decryptedUserName = Hash.decrypt(Hash.userNameKey, encyptedUserName);
        log.debug("Decrypted user-name to: " + decryptedUserName);
    } catch (GeneralSecurityException e) {
        log.error("Could not decrypt user name: " + e.toString());
    }
    return decryptedUserName;
}