Example usage for org.bouncycastle.crypto.paddings PKCS7Padding PKCS7Padding

List of usage examples for org.bouncycastle.crypto.paddings PKCS7Padding PKCS7Padding

Introduction

In this page you can find the example usage for org.bouncycastle.crypto.paddings PKCS7Padding PKCS7Padding.

Prototype

PKCS7Padding

Source Link

Usage

From source file:com.github.flbaue.jcrypttool.v2.domain.AesEncryptionService.java

License:Apache License

@Override
public InputStream decryptedInputStream(final Path path, final String password)
        throws IOException, DecryptionFailedException {
    try {//ww  w  .  j av  a 2s. co  m
        InputStream in = new BufferedInputStream(Files.newInputStream(path));
        byte[] initBlock = readInitBlock(in);
        byte[] salt = extractSalt(initBlock);
        byte[] iv = extractIV(initBlock);
        byte[] key = generateKey(password, salt);

        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()),
                new PKCS7Padding());
        KeyParameter keyParam = new KeyParameter(key);
        CipherParameters params = new ParametersWithIV(keyParam, iv);
        cipher.init(false, params);

        return new CipherInputStream(in, cipher);
    } catch (InvalidKeySpecException | NoSuchAlgorithmException e) {
        throw new DecryptionFailedException(e);
    }
}

From source file:com.github.flbaue.jcrypttool.v2.domain.AesEncryptionService.java

License:Apache License

@Override
public String decryptString(final String string, final String password) throws DecryptionFailedException {
    try {//w  w  w  .  j  ava2  s.  c  om
        byte[] inputBytes = Base64.decode(string);
        byte[] salt = extractSalt(inputBytes);
        byte[] iv = extractIV(inputBytes);
        byte[] key = generateKey(password, salt);
        byte[] encryptedData = extractEncryptedData(inputBytes);

        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()),
                new PKCS7Padding());
        KeyParameter keyParam = new KeyParameter(key);
        CipherParameters params = new ParametersWithIV(keyParam, iv);
        cipher.init(false, params);

        final byte out[] = new byte[cipher.getOutputSize(encryptedData.length)];
        int length = cipher.processBytes(encryptedData, 0, encryptedData.length, out, 0);
        byte[] result;

        length += cipher.doFinal(out, length);
        result = new byte[length];
        System.arraycopy(out, 0, result, 0, length);

        return new String(result);

    } catch (InvalidCipherTextException | InvalidKeySpecException | NoSuchAlgorithmException e) {
        throw new DecryptionFailedException(e);
    }
}

From source file:com.github.horrorho.inflatabledonkey.crypto.AESCBC.java

License:Open Source License

public static byte[] decryptAESCBC(byte[] key, byte[] iv, byte[] data) {
    // AES CBC PKCS7 decrypt
    try {/*from w  w  w.  jav a 2  s . c  o  m*/
        CipherParameters cipherParameters = new ParametersWithIV(new KeyParameter(key), iv);
        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(
                new CBCBlockCipher(new AESFastEngine()), new PKCS7Padding());
        cipher.init(false, cipherParameters);

        byte[] buffer = new byte[cipher.getOutputSize(data.length)];

        int pos = cipher.processBytes(data, 0, data.length, buffer, 0);
        pos += cipher.doFinal(buffer, pos);

        return Arrays.copyOf(buffer, pos);

    } catch (DataLengthException | IllegalStateException | InvalidCipherTextException ex) {
        throw new IllegalArgumentException("decrypt failed", ex);
    }
}

From source file:com.licel.jcardsim.crypto.SymmetricCipherImpl.java

License:Apache License

private void selectCipherEngine(Key theKey) {
    if (theKey == null) {
        CryptoException.throwIt(CryptoException.UNINITIALIZED_KEY);
    }//from  w  w w .  jav  a  2  s .co m
    if (!theKey.isInitialized()) {
        CryptoException.throwIt(CryptoException.UNINITIALIZED_KEY);
    }
    if (!(theKey instanceof SymmetricKeyImpl)) {
        CryptoException.throwIt(CryptoException.ILLEGAL_VALUE);
    }
    SymmetricKeyImpl key = (SymmetricKeyImpl) theKey;
    switch (algorithm) {
    case ALG_DES_CBC_NOPAD:
    case ALG_AES_BLOCK_128_CBC_NOPAD:
        engine = new BufferedBlockCipher(new CBCBlockCipher(key.getCipher()));
        break;
    case ALG_DES_CBC_ISO9797_M1:
        engine = new PaddedBufferedBlockCipher(new CBCBlockCipher(key.getCipher()), new ZeroBytePadding());
        break;
    case ALG_DES_CBC_ISO9797_M2:
        engine = new PaddedBufferedBlockCipher(new CBCBlockCipher(key.getCipher()), new ISO7816d4Padding());
        break;
    case ALG_DES_CBC_PKCS5:
        engine = new PaddedBufferedBlockCipher(new CBCBlockCipher(key.getCipher()), new PKCS7Padding());
        break;
    case ALG_DES_ECB_NOPAD:
    case ALG_AES_BLOCK_128_ECB_NOPAD:
        engine = new BufferedBlockCipher(key.getCipher());
        break;
    case ALG_DES_ECB_ISO9797_M1:
        engine = new PaddedBufferedBlockCipher(key.getCipher(), new ZeroBytePadding());
        break;
    case ALG_DES_ECB_ISO9797_M2:
        engine = new PaddedBufferedBlockCipher(key.getCipher(), new ISO7816d4Padding());
        break;
    case ALG_DES_ECB_PKCS5:
        engine = new PaddedBufferedBlockCipher(key.getCipher(), new PKCS7Padding());
        break;
    default:
        CryptoException.throwIt(CryptoException.NO_SUCH_ALGORITHM);
        break;
    }
}

From source file:com.licel.jcardsim.crypto.SymmetricSignatureImpl.java

License:Apache License

public void init(Key theKey, byte theMode, byte[] bArray, short bOff, short bLen) throws CryptoException {
    if (theKey == null) {
        CryptoException.throwIt(CryptoException.UNINITIALIZED_KEY);
    }/*from   ww  w .j a v a2s .  co m*/
    if (!theKey.isInitialized()) {
        CryptoException.throwIt(CryptoException.UNINITIALIZED_KEY);
    }
    if (!(theKey instanceof SymmetricKeyImpl)) {
        CryptoException.throwIt(CryptoException.ILLEGAL_VALUE);
    }
    CipherParameters cipherParams = null;
    BlockCipher cipher = ((SymmetricKeyImpl) theKey).getCipher();
    if (bArray == null) {
        cipherParams = ((SymmetricKeyImpl) theKey).getParameters();
    } else {
        if (bLen != cipher.getBlockSize()) {
            CryptoException.throwIt(CryptoException.ILLEGAL_VALUE);
        }
        cipherParams = new ParametersWithIV(((SymmetricKeyImpl) theKey).getParameters(), bArray, bOff, bLen);
    }
    switch (algorithm) {
    case ALG_DES_MAC4_NOPAD:
        engine = new CBCBlockCipherMac(cipher, 32, null);
        break;
    case ALG_DES_MAC8_NOPAD:
        engine = new CBCBlockCipherMac(cipher, 64, null);
        break;
    case ALG_DES_MAC4_ISO9797_M1:
        engine = new CBCBlockCipherMac(cipher, 32, new ZeroBytePadding());
        break;
    case ALG_DES_MAC8_ISO9797_M1:
        engine = new CBCBlockCipherMac(cipher, 64, new ZeroBytePadding());
        break;
    case ALG_DES_MAC4_ISO9797_M2:
        engine = new CBCBlockCipherMac(cipher, 32, new ISO7816d4Padding());
        break;
    case ALG_DES_MAC8_ISO9797_M2:
        engine = new CBCBlockCipherMac(cipher, 64, new ISO7816d4Padding());
        break;
    case ALG_DES_MAC8_ISO9797_1_M2_ALG3:
        engine = new ISO9797Alg3Mac(new DESEngine(), 64, new ISO7816d4Padding());
        break;
    case ALG_DES_MAC4_PKCS5:
        engine = new CBCBlockCipherMac(cipher, 32, new PKCS7Padding());
        break;
    case ALG_DES_MAC8_PKCS5:
        engine = new CBCBlockCipherMac(cipher, 64, new PKCS7Padding());
        break;
    case ALG_AES_MAC_128_NOPAD:
        engine = new CBCBlockCipherMac(cipher, 128, null);
        break;
    case ALG_HMAC_SHA1:
        engine = new HMac(new SHA1Digest());
        break;
    case ALG_HMAC_SHA_256:
        engine = new HMac(new SHA256Digest());
        break;
    case ALG_HMAC_SHA_384:
        engine = new HMac(new SHA384Digest());
        break;
    case ALG_HMAC_SHA_512:
        engine = new HMac(new SHA512Digest());
        break;
    case ALG_HMAC_MD5:
        engine = new HMac(new MD5Digest());
        break;
    case ALG_HMAC_RIPEMD160:
        engine = new HMac(new RIPEMD160Digest());
        break;
    default:
        CryptoException.throwIt(CryptoException.NO_SUCH_ALGORITHM);
        break;
    }
    engine.init(cipherParams);
    isInitialized = true;
}

From source file:com.logicoy.pdmp.pmpi.crypto.EncryptionClient.java

License:Apache License

public String getAES256Cipher(String inputText, String password, boolean decrypt) {
    KeyIVGenerator derivedFromPassword = new KeyIVGenerator(password);
    // Set up key and IV these are derived from the password, using MD5 very simple. See class details.

    try {//w  ww.j  a  va 2  s  .  c  o  m
        byte[] buffer;
        //Sting to encrypt
        if (!decrypt) {
            buffer = inputText.getBytes(Charset.forName("UTF-8"));
        } else {
            buffer = Base64.decode(inputText);
        }

        // Aes Encryption
        BlockCipher blockCipher = new AESEngine();

        // Mode CBC
        blockCipher = new CBCBlockCipher(blockCipher);

        BlockCipherPadding padding = new PKCS7Padding();

        // Get our Cipher.
        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(blockCipher, padding);

        // Initialize the cipher.
        cipher.init(!decrypt, new ParametersWithIV(new KeyParameter(derivedFromPassword.getKey()),
                derivedFromPassword.getIV()));
        //byte[] bytes_output = cipher.doFinal(buffer,0);
        byte bytes_output[] = new byte[cipher.getOutputSize(buffer.length)];
        int len = cipher.processBytes(buffer, 0, buffer.length, bytes_output, 0);
        int noOfBytesCopied = cipher.doFinal(bytes_output, len);

        if (!decrypt) {
            //Return base 64 encrypted text.
            return new String(Base64.encode(bytes_output), Charset.forName("UTF-8"));
            //return Convert.ToBase64String(bytes_output, Base64FormattingOptions.InsertLineBreaks);
        } else {
            //Return plain text.
            return new String(bytes_output, Charset.forName("UTF-8"));
        }

    } catch (Exception e) {
        logger.severe(" Failure attempting to AES256 encrypt/decrypt the xml " + e.toString());
        e.printStackTrace();
        throw new RuntimeException(" Failure attempting AES256 " + (decrypt ? "decryption" : "encryption")
                + " :" + e.getMessage());
    } finally {
        derivedFromPassword.Clean();
    }

}

From source file:com.vmware.admiral.common.security.EncryptorService.java

License:Open Source License

private BufferedBlockCipher getCipher(boolean forEncryption) {
    BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()),
            new PKCS7Padding());
    cipher.init(forEncryption, new ParametersWithIV(
            new KeyParameter(keyBytes, IV_LENGTH, keyBytes.length - IV_LENGTH), keyBytes, 0, IV_LENGTH));
    return cipher;
}

From source file:com._17od.upm.crypto.EncryptionService.java

License:Open Source License

public void initCipher(char[] password) throws InvalidPasswordException, NoSuchAlgorithmException,
        NoSuchPaddingException, InvalidKeyException, Exception {

    try {//w w  w .  j ava  2s  .  c  o m
        //Establishing Secure Channel
        SecureChannel(password);
        //SecureChannel();

        //Asking Card to be ready with Symm Key
        byte[] Data = new byte[password.length + salt.length];
        System.arraycopy(password.toString().getBytes(), 0, Data, 0, password.length);
        System.arraycopy(salt, 0, Data, password.length, salt.length);
        InterFaceApplet.SendAppletInstructionSecureChannel(PCSideCardInterface.SEND_INS_GENKEY, (byte) 0,
                (byte) 0, Data);

        //Generate Nounce for PC
        N_1 = generateSalt();
        byte[] Temp = new byte[N_1.length + 16];
        System.arraycopy(N_1, 0, Temp, 0, N_1.length);
        System.arraycopy("AAAAAAAAAAAAAAAA".getBytes(), 0, Temp, N_1.length, 16);
        byte[] res = new byte[32];
        cipher.doFinal(Temp, 0, 32, res, 0);

        //Send Ek(Nounce_PC || ID of PC)
        ResponseFromCard = InterFaceApplet.SendAppletInstructionSecureChannel(PCSideCardInterface.SEND_INS_N_1,
                (byte) 0, (byte) 0, res);

        //Received response from Card Nounce_PC || Nounce_Card || ID of Card

        //Decrypting Card Nounce
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        byte[] res1 = new byte[48];
        cipher.doFinal(ResponseFromCard, 0, 48, res1, 0);

        //Copying Nounce_PC
        byte[] res2 = new byte[16];
        System.arraycopy(res1, 0, res2, 0, 16);

        for (short i = 0; i < N_1.length; i++) {
            if (res2[i] != N_1[i]) {
                //If Nounce_PC is not matching throw error
                /*throw exception*/
                JOptionPane.showMessageDialog(mainWindow, Translator.translate("SecureChProblem"));
                System.exit(0);
            }
        }

        //Copying Nounce_Card
        System.arraycopy(res1, 16, N_B, 0, 16);

        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);

        cipher.doFinal(N_B, 0, 16, res2, 0);

        //Send Ek(Nounce_Card) 
        ResponseFromCard = InterFaceApplet.SendAppletInstructionSecureChannel(PCSideCardInterface.SEND_INS_N_B,
                (byte) 0, (byte) 0, res2);
        //Checking response from card for Nounce_Card
        if (ResponseFromCard == null) {
            //If Nounce_Card is not matching throw error
            /*throw exception*/
            JOptionPane.showMessageDialog(mainWindow, Translator.translate("SecureChProblem"));
            System.exit(0);
        }
        //Nounce_Card is Verified, then Generate Session Key      
        byte[] SessionKey = new byte[16];
        System.arraycopy(N_1, 0, res, 0, 16);
        System.arraycopy(N_B, 0, res, 16, 16);

        //HASH(Nounce_PC || Nounce_Card)
        MessageDigest sha = MessageDigest.getInstance("SHA-1");
        SessionKey = Arrays.copyOf(sha.digest(res), 16);

        //Initialing AES with Session Key
        sessionKeySpec = new SecretKeySpec(SessionKey, "AES");

        SKcipher = Cipher.getInstance("AES/ECB/NOPADDING");

        SKcipher.init(Cipher.DECRYPT_MODE, sessionKeySpec);

        //For New Database
        if (FileHandle == null) {
            //Asking for Handle from Card            
            FileHandle = InterFaceApplet.SendAppletInstruction(PCSideCardInterface.SEND_INS_SETKEY, (byte) 0,
                    (byte) 0, null, password);
        }
        //Asking Key from Card
        byte[] KeyFromCard1 = InterFaceApplet.SendAppletInstruction(PCSideCardInterface.SEND_INS_GETKEY,
                (byte) 0, (byte) 0, FileHandle, password);

        //Extracting Key from Card           
        System.arraycopy(KeyFromCard1, (short) 0, KeyFromCard, (short) 0, (short) 1);
        //Decrypting the key using Session Key
        SKcipher.doFinal(KeyFromCard1, (short) 1, (short) (KeyFromCard1.length - 1), KeyFromCard, (short) 1);

    } catch (InvalidPasswordException ex) {
        throw ex;
    }

    //Encryption/Decryption operation        
    KeyParameter keyParams = new KeyParameter(Util.cutArray(KeyFromCard, FileHandle_LENGTH, KeyLengthAES));

    encryptCipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), new PKCS7Padding());
    encryptCipher.init(true, keyParams);
    decryptCipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), new PKCS7Padding());
    decryptCipher.init(false, keyParams);

}

From source file:de.jpm.model.EncryptionService.java

License:Open Source License

/**
 *
 * @param password//from   w ww  . j  a v a 2  s  .  c o m
 */
public void initCipher(char[] password) {
    PBEParametersGenerator keyGenerator = new PKCS12ParametersGenerator(new SHA256Digest());
    keyGenerator.init(PKCS12ParametersGenerator.PKCS12PasswordToBytes(password), salt, 20);
    CipherParameters keyParams = keyGenerator.generateDerivedParameters(256, 128);

    encryptCipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), new PKCS7Padding());
    encryptCipher.init(true, keyParams);
    decryptCipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), new PKCS7Padding());
    decryptCipher.init(false, keyParams);
}

From source file:emailsecurity.AESBouncyCastle.java

public AESBouncyCastle() {
    this.blockCipherPadding = new PKCS7Padding();
    this.paddedBufferedBlockCipher = new PaddedBufferedBlockCipher(AESCipher, blockCipherPadding);
}