Search in sources :

Example 31 with NoSuchPaddingException

use of javax.crypto.NoSuchPaddingException in project LeafPic by HoraApps.

the class FingerprintHandler method initCipher.

public boolean initCipher() {
    try {
        cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7);
    } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
        throw new RuntimeException("Failed to get Cipher", e);
    }
    try {
        keyStore.load(null);
        SecretKey key = (SecretKey) keyStore.getKey(KEY_NAME, null);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return true;
    } catch (KeyPermanentlyInvalidatedException e) {
        return false;
    } catch (KeyStoreException | CertificateException | UnrecoverableKeyException | IOException | NoSuchAlgorithmException | InvalidKeyException e) {
        throw new RuntimeException("Failed to init Cipher", e);
    }
}
Also used : KeyPermanentlyInvalidatedException(android.security.keystore.KeyPermanentlyInvalidatedException) SecretKey(javax.crypto.SecretKey) UnrecoverableKeyException(java.security.UnrecoverableKeyException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) IOException(java.io.IOException) InvalidKeyException(java.security.InvalidKeyException)

Example 32 with NoSuchPaddingException

use of javax.crypto.NoSuchPaddingException in project carbon-apimgt by wso2.

the class FileEncryptionUtility method readFromEncryptedFile.

/**
 * Decrypts the content of an encrypted file and returns the text
 *
 * @param inputFilePath  absolute path of the encrypted file
 * @return content of the file after decryption
 * @throws APIManagementException if an error occurs while reading from the encrypted file
 */
public String readFromEncryptedFile(String inputFilePath) throws APIManagementException {
    CipherInputStream cipherInStream = null;
    ByteArrayOutputStream byteArrayOutStream = null;
    try {
        if (!Files.exists(Paths.get(inputFilePath))) {
            throw new APIManagementException("File to decrypt does not exist");
        }
        Cipher aesCipher = Cipher.getInstance(EncryptionConstants.AES);
        SecretKeySpec aesKeySpec = new SecretKeySpec(getAESKey(), EncryptionConstants.AES);
        aesCipher.init(Cipher.DECRYPT_MODE, aesKeySpec);
        cipherInStream = new CipherInputStream(APIFileUtils.readFileContentAsStream(inputFilePath), aesCipher);
        byteArrayOutStream = new ByteArrayOutputStream();
        IOUtils.copy(cipherInStream, byteArrayOutStream);
        byte[] outByteArray = byteArrayOutStream.toByteArray();
        log.debug("Successfully decrypted file using stored AES key");
        return new String(SecureVaultUtils.toChars(outByteArray));
    } catch (IOException | InvalidKeyException | NoSuchPaddingException | NoSuchAlgorithmException e) {
        String msg = "Error while decrypting file " + inputFilePath;
        throw new APIManagementException(msg, e);
    } finally {
        IOUtils.closeQuietly(cipherInStream);
        IOUtils.closeQuietly(byteArrayOutStream);
    }
}
Also used : CipherInputStream(javax.crypto.CipherInputStream) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) SecretKeySpec(javax.crypto.spec.SecretKeySpec) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Cipher(javax.crypto.Cipher) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException)

Example 33 with NoSuchPaddingException

use of javax.crypto.NoSuchPaddingException in project carbon-apimgt by wso2.

the class FileEncryptionUtility method encryptFile.

/**
 * Encrypts the contents of a file and stores it in a new file
 *
 * @param inputFilePath    absolute path of the file to encrypt
 * @param outputFilePath   expected absolute path of the new encrypted file
 * @throws APIManagementException  if an error occurs encrypting the file
 */
public void encryptFile(String inputFilePath, String outputFilePath) throws APIManagementException {
    InputStream inputStream = null;
    CipherOutputStream cipherOutStream = null;
    try {
        Cipher aesCipher = Cipher.getInstance(EncryptionConstants.AES);
        SecretKeySpec aesKeySpec = new SecretKeySpec(getAESKey(), EncryptionConstants.AES);
        aesCipher.init(Cipher.ENCRYPT_MODE, aesKeySpec);
        Files.deleteIfExists(Paths.get(outputFilePath));
        inputStream = APIFileUtils.readFileContentAsStream(inputFilePath);
        cipherOutStream = new CipherOutputStream(new FileOutputStream(outputFilePath), aesCipher);
        IOUtils.copy(inputStream, cipherOutStream);
        APIFileUtils.deleteFile(inputFilePath);
        log.debug("Successfully encrypted file using stored AES key");
    } catch (NoSuchPaddingException | NoSuchAlgorithmException | IOException | InvalidKeyException e) {
        String msg = "Error while encrypting the file at " + inputFilePath;
        throw new APIManagementException(msg, e);
    } finally {
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(cipherOutStream);
    }
}
Also used : CipherOutputStream(javax.crypto.CipherOutputStream) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) CipherInputStream(javax.crypto.CipherInputStream) InputStream(java.io.InputStream) SecretKeySpec(javax.crypto.spec.SecretKeySpec) FileOutputStream(java.io.FileOutputStream) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) Cipher(javax.crypto.Cipher) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) InvalidKeyException(java.security.InvalidKeyException)

Example 34 with NoSuchPaddingException

use of javax.crypto.NoSuchPaddingException in project Terasology by MovingBlocks.

the class ServerHandshakeHandler method processNewIdentityRequest.

private void processNewIdentityRequest(NetData.NewIdentityRequest newIdentityRequest, ChannelHandlerContext ctx) {
    logger.info("Received new identity request");
    try {
        byte[] preMasterSecret = config.getSecurity().getServerPrivateCertificate().decrypt(newIdentityRequest.getPreMasterSecret().toByteArray());
        byte[] masterSecret = HandshakeCommon.generateMasterSecret(preMasterSecret, newIdentityRequest.getRandom().toByteArray(), serverRandom);
        // Generate a certificate pair for the client
        CertificatePair clientCertificates = new CertificateGenerator().generate(config.getSecurity().getServerPrivateCertificate());
        NetData.CertificateSet certificateData = NetData.CertificateSet.newBuilder().setPublicCertificate(NetMessageUtil.convert(clientCertificates.getPublicCert())).setPrivateExponent(ByteString.copyFrom(clientCertificates.getPrivateCert().getExponent().toByteArray())).build();
        byte[] encryptedCert = null;
        try {
            SecretKeySpec key = HandshakeCommon.generateSymmetricKey(masterSecret, newIdentityRequest.getRandom().toByteArray(), serverRandom);
            Cipher cipher = Cipher.getInstance(IdentityConstants.SYMMETRIC_ENCRYPTION_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            encryptedCert = cipher.doFinal(certificateData.toByteArray());
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | BadPaddingException | IllegalBlockSizeException e) {
            logger.error("Unexpected error encrypting certificate for sending, ending connection attempt", e);
            ctx.getChannel().close();
            return;
        }
        ctx.getChannel().write(NetData.NetMessage.newBuilder().setProvisionIdentity(NetData.ProvisionIdentity.newBuilder().setEncryptedCertificates(ByteString.copyFrom(encryptedCert))).build());
        // Identity has been established, inform the server handler and withdraw from the pipeline
        ctx.getPipeline().remove(this);
        serverConnectionHandler.channelAuthenticated(clientCertificates.getPublicCert());
    } catch (BadEncryptedDataException e) {
        logger.error("Received invalid encrypted pre-master secret, ending connection attempt");
        ctx.getChannel().close();
    }
}
Also used : CertificateGenerator(org.terasology.identity.CertificateGenerator) NetData(org.terasology.protobuf.NetData) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) BadPaddingException(javax.crypto.BadPaddingException) InvalidKeyException(java.security.InvalidKeyException) BadEncryptedDataException(org.terasology.identity.BadEncryptedDataException) CertificatePair(org.terasology.identity.CertificatePair) SecretKeySpec(javax.crypto.spec.SecretKeySpec) Cipher(javax.crypto.Cipher)

Example 35 with NoSuchPaddingException

use of javax.crypto.NoSuchPaddingException in project Terasology by MovingBlocks.

the class PrivateIdentityCertificate method decrypt.

/**
 * Decrypts data encrypted by the paired public certificate
 *
 * @param data
 * @return The decrypted data
 * @throws BadEncryptedDataException If the data could not be decrypted due to an error with the data.
 */
public byte[] decrypt(byte[] data) throws BadEncryptedDataException {
    RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(modulus, exponent);
    try {
        KeyFactory keyFactory = KeyFactory.getInstance(IdentityConstants.CERTIFICATE_ALGORITHM);
        PrivateKey key = keyFactory.generatePrivate(keySpec);
        Cipher cipher = Cipher.getInstance(IdentityConstants.CERTIFICATE_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, key);
        return cipher.doFinal(data);
    } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
        throw new RuntimeException("Insufficient support for '" + IdentityConstants.CERTIFICATE_ALGORITHM + "', required for identity management", e);
    } catch (InvalidKeySpecException | InvalidKeyException e) {
        throw new RuntimeException("Unexpected error during encryption", e);
    } catch (BadPaddingException | IllegalBlockSizeException e) {
        throw new BadEncryptedDataException("Invalid encrypted data", e);
    }
}
Also used : PrivateKey(java.security.PrivateKey) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) BadPaddingException(javax.crypto.BadPaddingException) InvalidKeyException(java.security.InvalidKeyException) RSAPrivateKeySpec(java.security.spec.RSAPrivateKeySpec) Cipher(javax.crypto.Cipher) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) KeyFactory(java.security.KeyFactory)

Aggregations

NoSuchPaddingException (javax.crypto.NoSuchPaddingException)259 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)237 InvalidKeyException (java.security.InvalidKeyException)216 Cipher (javax.crypto.Cipher)187 IllegalBlockSizeException (javax.crypto.IllegalBlockSizeException)181 BadPaddingException (javax.crypto.BadPaddingException)180 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)119 SecretKeySpec (javax.crypto.spec.SecretKeySpec)91 IOException (java.io.IOException)83 IvParameterSpec (javax.crypto.spec.IvParameterSpec)66 SecretKey (javax.crypto.SecretKey)45 KeyStoreException (java.security.KeyStoreException)40 CertificateException (java.security.cert.CertificateException)40 UnrecoverableKeyException (java.security.UnrecoverableKeyException)35 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)30 UnsupportedEncodingException (java.io.UnsupportedEncodingException)27 NoSuchProviderException (java.security.NoSuchProviderException)27 GCMParameterSpec (javax.crypto.spec.GCMParameterSpec)18 FileNotFoundException (java.io.FileNotFoundException)16 SecureRandom (java.security.SecureRandom)16