Search in sources :

Example 56 with NoSuchPaddingException

use of javax.crypto.NoSuchPaddingException in project santuario-java by apache.

the class XMLCipher method constructCipher.

/**
 * Construct a Cipher object
 */
private Cipher constructCipher(String algorithm, String digestAlgorithm) throws XMLEncryptionException {
    String jceAlgorithm = JCEMapper.translateURItoJCEID(algorithm);
    LOG.debug("JCE Algorithm = {}", jceAlgorithm);
    Cipher c;
    try {
        if (requestedJCEProvider == null) {
            c = Cipher.getInstance(jceAlgorithm);
        } else {
            c = Cipher.getInstance(jceAlgorithm, requestedJCEProvider);
        }
    } catch (NoSuchAlgorithmException nsae) {
        // Check to see if an RSA OAEP MGF-1 with SHA-1 algorithm was requested
        // Some JDKs don't support RSA/ECB/OAEPPadding
        c = constructCipher(algorithm, digestAlgorithm, nsae);
    } catch (NoSuchProviderException nspre) {
        throw new XMLEncryptionException(nspre);
    } catch (NoSuchPaddingException nspae) {
        throw new XMLEncryptionException(nspae);
    }
    return c;
}
Also used : NoSuchPaddingException(javax.crypto.NoSuchPaddingException) Cipher(javax.crypto.Cipher) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) NoSuchProviderException(java.security.NoSuchProviderException)

Example 57 with NoSuchPaddingException

use of javax.crypto.NoSuchPaddingException in project keepass2android by PhilippC.

the class ImporterV3 method openDatabase.

public PwDatabaseV3 openDatabase(InputStream inStream, String password, InputStream keyfileStream, UpdateStatus status) throws IOException, InvalidDBException {
    PwDatabaseV3 newManager;
    // Load entire file, most of it's encrypted.
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    int nRead;
    byte[] data = new byte[16384];
    while ((nRead = inStream.read(data, 0, data.length)) != -1) {
        buffer.write(data, 0, nRead);
    }
    buffer.flush();
    int fileSize = buffer.size();
    // Pad with a blocksize (Twofish uses 128 bits), since Android 4.3 tries to write more to the buffer
    for (int i = 0; i < 16; i++) {
        buffer.write(0);
    }
    inStream.close();
    byte[] filebuf = buffer.toByteArray();
    // Parse header (unencrypted)
    if (fileSize < PwDbHeaderV3.BUF_SIZE)
        throw new IOException("File too short for header: " + fileSize + "<" + PwDbHeaderV3.BUF_SIZE);
    PwDbHeaderV3 hdr = new PwDbHeaderV3();
    hdr.loadFromFile(filebuf, 0);
    if ((hdr.signature1 != PwDbHeader.PWM_DBSIG_1) || (hdr.signature2 != PwDbHeaderV3.DBSIG_2)) {
        throw new InvalidDBSignatureException();
    }
    if (!hdr.matchesVersion()) {
        throw new InvalidDBVersionException();
    }
    newManager = createDB();
    newManager.setMasterKey(password, keyfileStream);
    // Select algorithm
    if ((hdr.flags & PwDbHeaderV3.FLAG_RIJNDAEL) != 0) {
        newManager.algorithm = PwEncryptionAlgorithm.Rjindal;
    } else if ((hdr.flags & PwDbHeaderV3.FLAG_TWOFISH) != 0) {
        newManager.algorithm = PwEncryptionAlgorithm.Twofish;
    } else {
        throw new InvalidAlgorithmException();
    }
    // Copy for testing
    newManager.copyHeader(hdr);
    newManager.numKeyEncRounds = hdr.numKeyEncRounds;
    newManager.name = "KeePass Password Manager";
    // Generate transformedMasterKey from masterKey
    newManager.makeFinalKey(hdr.masterSeed, hdr.transformSeed, newManager.numKeyEncRounds);
    // Initialize Rijndael algorithm
    Cipher cipher;
    try {
        if (newManager.algorithm == PwEncryptionAlgorithm.Rjindal) {
            cipher = CipherFactory.getInstance("AES/CBC/PKCS5Padding");
        } else if (newManager.algorithm == PwEncryptionAlgorithm.Twofish) {
            cipher = CipherFactory.getInstance("TWOFISH/CBC/PKCS7PADDING");
        } else {
            throw new IOException("Encryption algorithm is not supported");
        }
    } catch (NoSuchAlgorithmException e1) {
        throw new IOException("No such algorithm");
    } catch (NoSuchPaddingException e1) {
        throw new IOException("No such pdading");
    }
    try {
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(newManager.finalKey, "AES"), new IvParameterSpec(hdr.encryptionIV));
    } catch (InvalidKeyException e1) {
        throw new IOException("Invalid key");
    } catch (InvalidAlgorithmParameterException e1) {
        throw new IOException("Invalid algorithm parameter.");
    }
    // Decrypt! The first bytes aren't encrypted (that's the header)
    int encryptedPartSize;
    try {
        encryptedPartSize = cipher.doFinal(filebuf, PwDbHeaderV3.BUF_SIZE, fileSize - PwDbHeaderV3.BUF_SIZE, filebuf, PwDbHeaderV3.BUF_SIZE);
    } catch (ShortBufferException e1) {
        throw new IOException("Buffer too short");
    } catch (IllegalBlockSizeException e1) {
        throw new IOException("Invalid block size");
    } catch (BadPaddingException e1) {
        throw new InvalidPasswordException("Invalid key!");
    }
    // Copy decrypted data for testing
    newManager.copyEncrypted(filebuf, PwDbHeaderV3.BUF_SIZE, encryptedPartSize);
    MessageDigest md = null;
    try {
        md = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException e) {
        throw new IOException("No SHA-256 algorithm");
    }
    NullOutputStream nos = new NullOutputStream();
    DigestOutputStream dos = new DigestOutputStream(nos, md);
    dos.write(filebuf, PwDbHeaderV3.BUF_SIZE, encryptedPartSize);
    dos.close();
    byte[] hash = md.digest();
    if (!Arrays.equals(hash, hdr.contentsHash)) {
        Log.w("KeePassDroid", "Database file did not decrypt correctly. (checksum code is broken)");
        throw new InvalidPasswordException("Invalid key!");
    }
    // Import all groups
    int pos = PwDbHeaderV3.BUF_SIZE;
    PwGroupV3 newGrp = new PwGroupV3();
    for (int i = 0; i < hdr.numGroups; ) {
        int fieldType = LEDataInputStream.readUShort(filebuf, pos);
        pos += 2;
        int fieldSize = LEDataInputStream.readInt(filebuf, pos);
        pos += 4;
        if (fieldType == 0xFFFF) {
            // End-Group record.  Save group and count it.
            newGrp.populateBlankFields(newManager);
            newManager.groups.add(newGrp);
            newGrp = new PwGroupV3();
            i++;
        } else {
            readGroupField(newManager, newGrp, fieldType, filebuf, pos);
        }
        pos += fieldSize;
    }
    // Import all entries
    PwEntryV3 newEnt = new PwEntryV3();
    for (int i = 0; i < hdr.numEntries; ) {
        int fieldType = LEDataInputStream.readUShort(filebuf, pos);
        int fieldSize = LEDataInputStream.readInt(filebuf, pos + 2);
        if (fieldType == 0xFFFF) {
            // End-Group record.  Save group and count it.
            newEnt.populateBlankFields(newManager);
            newManager.entries.add(newEnt);
            newEnt = new PwEntryV3();
            i++;
        } else {
            readEntryField(newManager, newEnt, filebuf, pos);
        }
        pos += 2 + 4 + fieldSize;
    }
    newManager.constructTree(null);
    return newManager;
}
Also used : PwEntryV3(com.keepassdroid.database.PwEntryV3) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) InvalidDBSignatureException(com.keepassdroid.database.exception.InvalidDBSignatureException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) BadPaddingException(javax.crypto.BadPaddingException) InvalidDBVersionException(com.keepassdroid.database.exception.InvalidDBVersionException) PwDatabaseV3(com.keepassdroid.database.PwDatabaseV3) SecretKeySpec(javax.crypto.spec.SecretKeySpec) DigestOutputStream(java.security.DigestOutputStream) InvalidPasswordException(com.keepassdroid.database.exception.InvalidPasswordException) MessageDigest(java.security.MessageDigest) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) PwDbHeaderV3(com.keepassdroid.database.PwDbHeaderV3) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) InvalidKeyException(java.security.InvalidKeyException) InvalidAlgorithmException(com.keepassdroid.database.exception.InvalidAlgorithmException) PwGroupV3(com.keepassdroid.database.PwGroupV3) ShortBufferException(javax.crypto.ShortBufferException) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) NullOutputStream(com.keepassdroid.stream.NullOutputStream)

Example 58 with NoSuchPaddingException

use of javax.crypto.NoSuchPaddingException in project keepass2android by PhilippC.

the class AndroidFinalKey method transformMasterKey.

@Override
public byte[] transformMasterKey(byte[] pKeySeed, byte[] pKey, int rounds) throws IOException {
    Cipher cipher;
    try {
        cipher = Cipher.getInstance("AES/ECB/NoPadding");
    } catch (NoSuchAlgorithmException e) {
        throw new IOException("NoSuchAlgorithm: " + e.getMessage());
    } catch (NoSuchPaddingException e) {
        throw new IOException("NoSuchPadding: " + e.getMessage());
    }
    try {
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(pKeySeed, "AES"));
    } catch (InvalidKeyException e) {
        throw new IOException("InvalidPasswordException: " + e.getMessage());
    }
    // Encrypt key rounds times
    byte[] newKey = new byte[pKey.length];
    System.arraycopy(pKey, 0, newKey, 0, pKey.length);
    byte[] destKey = new byte[pKey.length];
    for (int i = 0; i < rounds; i++) {
        try {
            cipher.update(newKey, 0, newKey.length, destKey, 0);
            System.arraycopy(destKey, 0, newKey, 0, newKey.length);
        } catch (ShortBufferException e) {
            throw new IOException("Short buffer: " + e.getMessage());
        }
    }
    // Hash the key
    MessageDigest md = null;
    try {
        md = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException e) {
        assert true;
        throw new IOException("SHA-256 not implemented here: " + e.getMessage());
    }
    md.update(newKey);
    return md.digest();
}
Also used : SecretKeySpec(javax.crypto.spec.SecretKeySpec) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) ShortBufferException(javax.crypto.ShortBufferException) Cipher(javax.crypto.Cipher) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) InvalidKeyException(java.security.InvalidKeyException) MessageDigest(java.security.MessageDigest)

Example 59 with NoSuchPaddingException

use of javax.crypto.NoSuchPaddingException in project commons by terran4j.

the class AsymmetricKeys method initCipher.

private Cipher initCipher(RSAPrivateKey privateKey) throws BusinessException {
    try {
        Cipher cipher = Cipher.getInstance(ALGORITHM_RSA, new BouncyCastleProvider());
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return cipher;
    } catch (NoSuchAlgorithmException e) {
        throw new BusinessException(CommonErrorCode.INTERNAL_ERROR, e).put("algorithm", ALGORITHM_RSA).setMessage("No Such Algorithm: ${algorithm}");
    } catch (NoSuchPaddingException e) {
        throw new BusinessException(CommonErrorCode.INTERNAL_ERROR, e).setMessage("No Such Padding");
    } catch (InvalidKeyException e) {
        throw new BusinessException(CommonErrorCode.INTERNAL_ERROR, e).setMessage("解密私钥非法,请检查");
    }
}
Also used : BusinessException(com.terran4j.commons.util.error.BusinessException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) Cipher(javax.crypto.Cipher) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 60 with NoSuchPaddingException

use of javax.crypto.NoSuchPaddingException in project Pix-Art-Messenger by kriztan.

the class WelcomeActivity method checkDatabase.

private void checkDatabase(String DecryptionKey) throws IOException {
    // Set the folder on the SDcard
    File directory = new File(FileBackend.getConversationsDirectory("Database", false));
    // Set the input file stream up:
    FileInputStream InputFile = new FileInputStream(directory.getPath() + "/database.db.crypt");
    // Temp output for DB checks
    File TempFile = new File(directory.getPath() + "/database.bak");
    FileOutputStream OutputTemp = new FileOutputStream(TempFile);
    try {
        EncryptDecryptFile.decrypt(InputFile, OutputTemp, DecryptionKey);
    } catch (NoSuchAlgorithmException e) {
        Log.d(Config.LOGTAG, "Database importer: decryption failed with " + e);
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        Log.d(Config.LOGTAG, "Database importer: decryption failed with " + e);
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        Log.d(Config.LOGTAG, "Database importer: decryption failed (invalid key) with " + e);
        e.printStackTrace();
    } catch (IOException e) {
        Log.d(Config.LOGTAG, "Database importer: decryption failed (IO) with " + e);
        e.printStackTrace();
    }
    SQLiteDatabase checkDB = null;
    int DB_Version = DatabaseBackend.DATABASE_VERSION;
    int Backup_DB_Version = 0;
    try {
        String dbPath = TempFile.toString();
        checkDB = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READONLY);
        Backup_DB_Version = checkDB.getVersion();
        Log.d(Config.LOGTAG, "Backup found: " + checkDB + " Version: " + checkDB.getVersion());
    } catch (SQLiteException e) {
        // database does't exist yet.
        Log.d(Config.LOGTAG, "No backup found: " + checkDB);
    }
    if (checkDB != null) {
        checkDB.close();
    }
    Log.d(Config.LOGTAG, "checkDB = " + checkDB.toString() + ", Backup DB = " + Backup_DB_Version + ", DB = " + DB_Version);
    if (checkDB != null && Backup_DB_Version != 0 && Backup_DB_Version <= DB_Version) {
        try {
            ImportDatabase();
            importSuccessful = true;
        } catch (Exception e) {
            importSuccessful = false;
            e.printStackTrace();
        } finally {
            if (importSuccessful) {
                restart();
            }
        }
    } else if (checkDB != null && Backup_DB_Version == 0) {
        WelcomeActivity.this.runOnUiThread(new Runnable() {

            public void run() {
                Toast.makeText(WelcomeActivity.this, R.string.Password_wrong, Toast.LENGTH_LONG).show();
                enterPasswordDialog();
            }
        });
    } else {
        WelcomeActivity.this.runOnUiThread(new Runnable() {

            public void run() {
                Toast.makeText(WelcomeActivity.this, R.string.Import_failed, Toast.LENGTH_LONG).show();
            }
        });
    }
}
Also used : NoSuchPaddingException(javax.crypto.NoSuchPaddingException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) InvalidKeyException(java.security.InvalidKeyException) SQLiteException(android.database.sqlite.SQLiteException) FileInputStream(java.io.FileInputStream) SQLiteException(android.database.sqlite.SQLiteException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) SQLiteDatabase(android.database.sqlite.SQLiteDatabase) FileOutputStream(java.io.FileOutputStream) EncryptDecryptFile(de.pixart.messenger.utils.EncryptDecryptFile) File(java.io.File)

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