Example usage for java.security GeneralSecurityException GeneralSecurityException

List of usage examples for java.security GeneralSecurityException GeneralSecurityException

Introduction

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

Prototype

public GeneralSecurityException(Throwable cause) 

Source Link

Document

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

Usage

From source file:org.jvnet.hudson.update_center.Signing.java

/**
 * Generates a canonicalized JSON format of the given object, and put the signature in it.
 * Because it mutates the signed object itself, validating the signature needs a bit of work,
 * but this enables a signature to be added transparently.
 *//*from w  ww  .  j av a 2 s .com*/
public void sign(JSONObject o) throws GeneralSecurityException, IOException {
    JSONObject sign = new JSONObject();

    List<X509Certificate> certs = getCertificateChain();
    X509Certificate signer = certs.get(0); // the first one is the signer, and the rest is the chain to a root CA.

    // this is for computing a digest
    MessageDigest sha1 = MessageDigest.getInstance("SHA1");
    DigestOutputStream dos = new DigestOutputStream(new NullOutputStream(), sha1);

    // this is for computing a signature
    PrivateKey key = ((KeyPair) new PEMReader(new FileReader(privateKey)).readObject()).getPrivate();
    Signature sig = Signature.getInstance("SHA1withRSA");
    sig.initSign(key);
    SignatureOutputStream sos = new SignatureOutputStream(sig);

    // this is for verifying that signature validates
    Signature verifier = Signature.getInstance("SHA1withRSA");
    verifier.initVerify(signer.getPublicKey());
    SignatureOutputStream vos = new SignatureOutputStream(verifier);

    o.writeCanonical(new OutputStreamWriter(new TeeOutputStream(new TeeOutputStream(dos, sos), vos), "UTF-8"));

    // digest
    byte[] digest = sha1.digest();
    sign.put("digest", new String(Base64.encodeBase64(digest)));

    // signature
    byte[] s = sig.sign();
    sign.put("signature", new String(Base64.encodeBase64(s)));

    // and certificate chain
    JSONArray a = new JSONArray();
    for (X509Certificate cert : certs)
        a.add(new String(Base64.encodeBase64(cert.getEncoded())));
    sign.put("certificates", a);

    // did the signature validate?
    if (!verifier.verify(s))
        throw new GeneralSecurityException(
                "Signature failed to validate. Either the certificate and the private key weren't matching, or a bug in the program.");

    o.put("signature", sign);
}

From source file:com.nokia.example.pepperfarm.iap.Payment.java

/**
 * Binds to Nokia in-app payment service.
 *
 * @param ctx/* w w w. j  a va2s. co m*/
 * @throws GeneralSecurityException If Nokia In-App payment enabler fingerprint is not valid
 */
public void connectToService(Context ctx) throws GeneralSecurityException {

    activity = (Activity) ctx;

    //Verifies enabler fingerprint
    if (!verifyFingreprint()) {

        npayAvailable = false;
        errorAlert("Nokia In-App Payment Enabler is not available.");

        throw new GeneralSecurityException("Enabler fingerprint incorrect. Billing unavailable");

    } else {
        //Enabler fingerprint OK. Continue with binding. 
        Intent paymentEnabler = new Intent("com.nokia.payment.iapenabler.InAppBillingService.BIND");
        paymentEnabler.setPackage(ENABLER_PACKAGENAME);
        activity.bindService(paymentEnabler, this, Context.BIND_AUTO_CREATE);
    }
}

From source file:org.glite.slcs.pki.bouncycastle.PKCS10.java

/**
 * Private constructor.//from  ww  w  . j  a v a2s .c o m
 * 
 * @param pkcs10
 *            The {@link PKCS10CertificationRequest} to wrap.
 * @throws GeneralSecurityException
 *             if the {@link PKCS10CertificationRequest} can not be
 *             verified.
 */
private PKCS10(PKCS10CertificationRequest pkcs10) throws GeneralSecurityException {
    this.bcPKCS10_ = pkcs10;
    if (!bcPKCS10_.verify()) {
        LOG.error("Failed to verify the PKCS#10");
        throw new GeneralSecurityException("PKCS#10 verification failed");
    }

}

From source file:piecework.security.concrete.DefaultEncryptionKeyProvider.java

@Override
public SecretKeyRing getEncryptionKeyRing(String processDefinitionKey, String processInstanceId)
        throws GeneralSecurityException {
    String encryptionKeyName = null;

    // If encryption key name is not provided, then
    if (StringUtils.isEmpty(encryptionKeyName)) {
        int numberOfEncryptionKeys = encryptKeyNames.size();
        if (numberOfEncryptionKeys <= 0)
            throw new GeneralSecurityException("No encryption keys provided");

        int index = numberOfEncryptionKeys == 1 ? 0 : random.nextInt(numberOfEncryptionKeys);
        encryptionKeyName = encryptKeyNames.get(index);
    }//ww w .j  av  a2s.c  o m

    SecretKey secretKey = encryptKeyMap.get(encryptionKeyName);
    if (secretKey == null)
        throw new GeneralSecurityException("Misconfigured - encryption key with no secret key in map");

    return new SecretKeyRing(encryptionKeyName, secretKey);
}

From source file:uk.ac.ox.webauth.crypto.Des3CbcSha1Kd.java

@Override
public ASN1Encodable decrypt(byte[] cipherData) throws IOException, GeneralSecurityException {
    // derive our decryption and hmac keys as per RFC 3961
    // first work out the "well known constant"s for the different keys
    byte[] wkcKe = new byte[5];
    wkcKe[0] = (byte) ((keyUsage >> 24) & 0xFF);
    wkcKe[1] = (byte) ((keyUsage >> 16) & 0xFF);
    wkcKe[2] = (byte) ((keyUsage >> 8) & 0xFF);
    wkcKe[3] = (byte) (keyUsage & 0xFF);
    wkcKe[4] = (byte) 0xAA;
    byte[] wkcKi = (byte[]) wkcKe.clone();
    wkcKi[4] = (byte) 0x55;

    // then make the keys
    // RFC 3961: Derived Key = DK(Base Key, Well-Known Constant)
    SecretKey ke = new SecretKeySpec(dk(key.getEncoded(), wkcKe), "DESede");
    SecretKey ki = new SecretKeySpec(dk(key.getEncoded(), wkcKi), "DESede");

    // set up the HMAC object so we can get the length
    Mac hmacSHA1 = Mac.getInstance("HmacSHA1");
    hmacSHA1.init(ki);//w  ww .j  a v a 2 s  . c  o  m
    int hmacLength = hmacSHA1.getMacLength();

    // first split the checksum off the data
    InputStream is = new ByteArrayInputStream(cipherData);
    byte[] data = new byte[cipherData.length - hmacLength];
    if (is.read(data) != data.length) {
        throw new IOException("Couldn't read all the encrypted data.");
    }
    byte[] checksum = new byte[hmacLength];
    if (is.read(checksum) != checksum.length) {
        throw new IOException("Couldn't read all the checksum data.");
    }

    // then decrypt the data
    Cipher cipher = Cipher.getInstance("DESede/CBC/NoPadding");
    cipher.init(DECRYPT_MODE, ke, IV);
    byte[] decrypted = cipher.doFinal(data);

    // check the HMAC
    byte[] newChecksum = hmacSHA1.doFinal(decrypted);
    if (!Arrays.equals(checksum, newChecksum)) {
        throw new GeneralSecurityException("Checksum failure.");
        //System.out.println("Checksum failed.");
    }

    // throw away the confounder and then return an ASN.1 encodable object
    is = new ByteArrayInputStream(decrypted);
    is.skip(cipher.getBlockSize());
    ASN1InputStream ais = new ASN1InputStream(is);
    return (ASN1Encodable) ais.readObject();
}

From source file:fr.cls.atoll.motu.library.misc.vfs.provider.gsiftp.ProxyTool.java

/**
 * Load user key & decrypt it./*from   w  w  w.j ava 2s . c om*/
 * 
 * @param keyPath pth to the key
 * @param pwd decryption passphrase
 * 
 * @throws GeneralSecurityException the general security exception
 */
private void loadKey(String keyPath, String pwd) throws GeneralSecurityException {
    try {
        OpenSSLKey key = new BouncyCastleOpenSSLKey(keyPath);

        if (key.isEncrypted()) {
            key.decrypt(pwd);
        }

        userKey = key.getPrivateKey();

    } catch (IOException e) {
        throw new GeneralSecurityException("Error: Failed to load key: " + keyPath);
    } catch (GeneralSecurityException e) {
        throw new GeneralSecurityException("Error: Wrong pass phrase");
    }
}

From source file:piecework.security.concrete.DefaultEncryptionKeyProvider.java

@Override
public SecretKey getDecryptionKey(String encryptionKeyName) throws GeneralSecurityException {
    SecretKey secretKey = decryptKeyMap.get(encryptionKeyName);
    if (secretKey == null)
        throw new GeneralSecurityException("Misconfigured - decryption key with no secret key in map");

    return secretKey;
}

From source file:com.oneops.cms.crypto.CmsCryptoDES.java

private String decryptStr(String instr) throws GeneralSecurityException {
    if (StringUtils.isEmpty(instr)) {
        return instr;
    }//from   ww  w.  j  a  v a2s .c om
    long t1 = System.currentTimeMillis();
    PaddedBufferedBlockCipher decryptor = new PaddedBufferedBlockCipher(new CBCBlockCipher(new DESedeEngine()));
    decryptor.init(false, keyParameter);
    byte[] in = null;
    byte[] cipherText = null;

    try {
        in = Hex.decode(instr);
        cipherText = new byte[decryptor.getOutputSize(in.length)];

        int outputLen = decryptor.processBytes(in, 0, in.length, cipherText, 0);
        decryptor.doFinal(cipherText, outputLen);
    } catch (Exception e) {
        throw new GeneralSecurityException(e);
    }
    long t2 = System.currentTimeMillis();
    logger.debug("Time taken to decrypt(millis) : " + (t2 - t1));
    return (new String(cipherText)).replaceAll("\\u0000+$", "");
}

From source file:org.globus.gsi.util.CertificateLoadUtil.java

/**
 * Loads multiple X.509 certificates from the specified file. Each
 * certificate must be in PEM/Base64 format and start with "BEGIN
 * CERTIFICATE" and end with "END CERTIFICATE" line.
 *
 * @param file the certificate file to load the certificate from.
 * @return an array of certificates loaded from the file.
 * @throws IOException              if I/O error occurs
 * @throws GeneralSecurityException if security problems occurs.
 *///from  ww w  . j a  va2  s  . com
public static X509Certificate[] loadCertificates(String file) throws IOException, GeneralSecurityException {

    if (file == null) {
        throw new IllegalArgumentException("Certificate file is null");
        //i18n
        //                                 .getMessage("certFileNull"));
    }

    List<X509Certificate> list = new ArrayList<X509Certificate>();
    BufferedReader reader = new BufferedReader(new FileReader(file));
    X509Certificate cert = readCertificate(reader);
    try {
        while (cert != null) {
            list.add(cert);
            cert = readCertificate(reader);
        }
    } finally {
        reader.close();
    }

    if (list.size() == 0) {
        throw new GeneralSecurityException("No certificate data");
        //i18n.getMessage("noCertData"));
    }

    int size = list.size();
    return list.toArray(new X509Certificate[size]);
}

From source file:org.apache.nifi.toolkit.tls.util.TlsHelper.java

public static String writeKeyStore(KeyStore keyStore, OutputStreamFactory outputStreamFactory, File file,
        String password, boolean generatedPassword) throws IOException, GeneralSecurityException {
    try (OutputStream fileOutputStream = outputStreamFactory.create(file)) {
        keyStore.store(fileOutputStream, password.toCharArray());
    } catch (IOException e) {
        if (e.getMessage().toLowerCase().contains(ILLEGAL_KEY_SIZE)
                && !isUnlimitedStrengthCryptographyEnabled()) {
            if (generatedPassword) {
                file.delete();//from   w ww  .  j av  a  2 s .  c om
                String truncatedPassword = password.substring(0, 7);
                try (OutputStream fileOutputStream = outputStreamFactory.create(file)) {
                    keyStore.store(fileOutputStream, truncatedPassword.toCharArray());
                }
                logTruncationWarning(file);
                return truncatedPassword;
            } else {
                throw new GeneralSecurityException("Specified password for " + file
                        + " too long to work without unlimited JCE policy installed." + System.lineSeparator()
                        + "Please see " + JCE_URL);
            }
        } else {
            throw e;
        }
    }
    return password;
}