Search in sources :

Example 41 with GeneralSecurityException

use of java.security.GeneralSecurityException in project lucene-solr by apache.

the class CryptoKeys method decodeAES.

public static String decodeAES(String base64CipherTxt, String pwd, final int keySizeBits) {
    final Charset ASCII = Charset.forName("ASCII");
    final int INDEX_KEY = 0;
    final int INDEX_IV = 1;
    final int ITERATIONS = 1;
    final int SALT_OFFSET = 8;
    final int SALT_SIZE = 8;
    final int CIPHERTEXT_OFFSET = SALT_OFFSET + SALT_SIZE;
    try {
        byte[] headerSaltAndCipherText = Base64.base64ToByteArray(base64CipherTxt);
        // --- extract salt & encrypted ---
        // header is "Salted__", ASCII encoded, if salt is being used (the default)
        byte[] salt = Arrays.copyOfRange(headerSaltAndCipherText, SALT_OFFSET, SALT_OFFSET + SALT_SIZE);
        byte[] encrypted = Arrays.copyOfRange(headerSaltAndCipherText, CIPHERTEXT_OFFSET, headerSaltAndCipherText.length);
        // --- specify cipher and digest for evpBytesTokey method ---
        Cipher aesCBC = Cipher.getInstance("AES/CBC/PKCS5Padding");
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        // --- create key and IV  ---
        // the IV is useless, OpenSSL might as well have use zero's
        final byte[][] keyAndIV = evpBytesTokey(keySizeBits / Byte.SIZE, aesCBC.getBlockSize(), md5, salt, pwd.getBytes(ASCII), ITERATIONS);
        SecretKeySpec key = new SecretKeySpec(keyAndIV[INDEX_KEY], "AES");
        IvParameterSpec iv = new IvParameterSpec(keyAndIV[INDEX_IV]);
        // --- initialize cipher instance and decrypt ---
        aesCBC.init(Cipher.DECRYPT_MODE, key, iv);
        byte[] decrypted = aesCBC.doFinal(encrypted);
        return new String(decrypted, ASCII);
    } catch (BadPaddingException e) {
        // AKA "something went wrong"
        throw new IllegalStateException("Bad password, algorithm, mode or padding;" + " no salt, wrong number of iterations or corrupted ciphertext.", e);
    } catch (IllegalBlockSizeException e) {
        throw new IllegalStateException("Bad algorithm, mode or corrupted (resized) ciphertext.", e);
    } catch (GeneralSecurityException e) {
        throw new IllegalStateException(e);
    }
}
Also used : GeneralSecurityException(java.security.GeneralSecurityException) Charset(java.nio.charset.Charset) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) BadPaddingException(javax.crypto.BadPaddingException) SecretKeySpec(javax.crypto.spec.SecretKeySpec) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) MessageDigest(java.security.MessageDigest)

Example 42 with GeneralSecurityException

use of java.security.GeneralSecurityException in project lucene-solr by apache.

the class SimplePostTool method postData.

/**
   * Reads data from the data stream and posts it to solr,
   * writes to the response to output
   * @return true if success
   */
public boolean postData(InputStream data, Long length, OutputStream output, String type, URL url) {
    if (mockMode)
        return true;
    boolean success = true;
    if (type == null)
        type = DEFAULT_CONTENT_TYPE;
    HttpURLConnection urlc = null;
    try {
        try {
            urlc = (HttpURLConnection) url.openConnection();
            try {
                urlc.setRequestMethod("POST");
            } catch (ProtocolException e) {
                fatal("Shouldn't happen: HttpURLConnection doesn't support POST??" + e);
            }
            urlc.setDoOutput(true);
            urlc.setDoInput(true);
            urlc.setUseCaches(false);
            urlc.setAllowUserInteraction(false);
            urlc.setRequestProperty("Content-type", type);
            basicAuth(urlc);
            if (null != length) {
                urlc.setFixedLengthStreamingMode(length);
            } else {
                //use JDK default chunkLen, 4k in Java 8.
                urlc.setChunkedStreamingMode(-1);
            }
            urlc.connect();
        } catch (IOException e) {
            fatal("Connection error (is Solr running at " + solrUrl + " ?): " + e);
            success = false;
        } catch (Exception e) {
            fatal("POST failed with error " + e.getMessage());
        }
        try (final OutputStream out = urlc.getOutputStream()) {
            pipe(data, out);
        } catch (IOException e) {
            fatal("IOException while posting data: " + e);
        }
        try {
            success &= checkResponseCode(urlc);
            try (final InputStream in = urlc.getInputStream()) {
                pipe(in, output);
            }
        } catch (IOException e) {
            warn("IOException while reading response: " + e);
            success = false;
        } catch (GeneralSecurityException e) {
            fatal("Looks like Solr is secured and would not let us in. Try with another user in '-u' parameter");
        }
    } finally {
        if (urlc != null)
            urlc.disconnect();
    }
    return success;
}
Also used : ProtocolException(java.net.ProtocolException) HttpURLConnection(java.net.HttpURLConnection) GZIPInputStream(java.util.zip.GZIPInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InflaterInputStream(java.util.zip.InflaterInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) XPathExpressionException(javax.xml.xpath.XPathExpressionException) GeneralSecurityException(java.security.GeneralSecurityException) PatternSyntaxException(java.util.regex.PatternSyntaxException) SAXException(org.xml.sax.SAXException) BufferOverflowException(java.nio.BufferOverflowException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) ProtocolException(java.net.ProtocolException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Example 43 with GeneralSecurityException

use of java.security.GeneralSecurityException in project poi by apache.

the class InternalWorkbook method updateEncryptionRecord.

private void updateEncryptionRecord() {
    FilePassRecord fpr = (FilePassRecord) findFirstRecordBySid(FilePassRecord.sid);
    String password = Biff8EncryptionKey.getCurrentUserPassword();
    if (password == null) {
        if (fpr != null) {
            // need to remove password data
            records.remove(fpr);
        }
    } else {
        // create password record
        if (fpr == null) {
            fpr = new FilePassRecord(EncryptionMode.binaryRC4);
            records.add(1, fpr);
        }
        // check if the password has been changed
        EncryptionInfo ei = fpr.getEncryptionInfo();
        byte[] encVer = ei.getVerifier().getEncryptedVerifier();
        try {
            Decryptor dec = ei.getDecryptor();
            Encryptor enc = ei.getEncryptor();
            if (encVer == null || !dec.verifyPassword(password)) {
                enc.confirmPassword(password);
            } else {
                SecretKey sk = dec.getSecretKey();
                ei.getEncryptor().setSecretKey(sk);
            }
        } catch (GeneralSecurityException e) {
            throw new EncryptedDocumentException("can't validate/update encryption setting", e);
        }
    }
}
Also used : FilePassRecord(org.apache.poi.hssf.record.FilePassRecord) SecretKey(javax.crypto.SecretKey) Decryptor(org.apache.poi.poifs.crypt.Decryptor) EncryptedDocumentException(org.apache.poi.EncryptedDocumentException) EncryptionInfo(org.apache.poi.poifs.crypt.EncryptionInfo) GeneralSecurityException(java.security.GeneralSecurityException) Encryptor(org.apache.poi.poifs.crypt.Encryptor) UnicodeString(org.apache.poi.hssf.record.common.UnicodeString)

Example 44 with GeneralSecurityException

use of java.security.GeneralSecurityException in project poi by apache.

the class ChunkedCipherOutputStream method close.

@Override
public void close() throws IOException {
    if (isClosed) {
        LOG.log(POILogger.DEBUG, "ChunkedCipherOutputStream was already closed - ignoring");
        return;
    }
    isClosed = true;
    try {
        writeChunk(false);
        super.close();
        if (fileOut != null) {
            int oleStreamSize = (int) (fileOut.length() + LittleEndianConsts.LONG_SIZE);
            calculateChecksum(fileOut, (int) pos);
            dir.createDocument(DEFAULT_POIFS_ENTRY, oleStreamSize, new EncryptedPackageWriter());
            createEncryptionInfoEntry(dir, fileOut);
        }
    } catch (GeneralSecurityException e) {
        throw new IOException(e);
    }
}
Also used : GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException)

Example 45 with GeneralSecurityException

use of java.security.GeneralSecurityException in project poi by apache.

the class ChunkedCipherInputStream method read.

private int read(byte[] b, int off, int len, boolean readPlain) throws IOException {
    int total = 0;
    if (available() <= 0) {
        return -1;
    }
    final int chunkMask = getChunkMask();
    while (len > 0) {
        if (!chunkIsValid) {
            try {
                nextChunk();
                chunkIsValid = true;
            } catch (GeneralSecurityException e) {
                throw new EncryptedDocumentException(e.getMessage(), e);
            }
        }
        int count = (int) (chunk.length - (pos & chunkMask));
        int avail = available();
        if (avail == 0) {
            return total;
        }
        count = Math.min(avail, Math.min(count, len));
        System.arraycopy(readPlain ? plain : chunk, (int) (pos & chunkMask), b, off, count);
        off += count;
        len -= count;
        pos += count;
        if ((pos & chunkMask) == 0) {
            chunkIsValid = false;
        }
        total += count;
    }
    return total;
}
Also used : EncryptedDocumentException(org.apache.poi.EncryptedDocumentException) GeneralSecurityException(java.security.GeneralSecurityException)

Aggregations

GeneralSecurityException (java.security.GeneralSecurityException)1197 IOException (java.io.IOException)448 Cipher (javax.crypto.Cipher)148 Test (org.junit.Test)136 X509Certificate (java.security.cert.X509Certificate)130 KeyStore (java.security.KeyStore)98 SSLContext (javax.net.ssl.SSLContext)86 SecretKeySpec (javax.crypto.spec.SecretKeySpec)82 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)77 ArrayList (java.util.ArrayList)75 File (java.io.File)64 InputStream (java.io.InputStream)63 Certificate (java.security.cert.Certificate)61 PublicKey (java.security.PublicKey)56 FileInputStream (java.io.FileInputStream)54 PrivateKey (java.security.PrivateKey)51 BigInteger (java.math.BigInteger)50 SecretKey (javax.crypto.SecretKey)48 IvParameterSpec (javax.crypto.spec.IvParameterSpec)47 KeyPair (java.security.KeyPair)45