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:net.nharyes.secrete.curve.Curve25519PrivateKey.java

License:Open Source License

public void serialize(OutputStream out, char[] password) throws IOException {

    try {//from w ww . j  a va  2 s. c o  m

        // generate initial vector
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        byte[] iv = new byte[16];
        random.nextBytes(iv);

        // generate salt
        byte[] salt = new byte[64];
        random.nextBytes(salt);

        // initialize cipher
        CipherParameters params = new ParametersWithIV(new KeyParameter(deriveKey(password, salt)), iv);
        BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()),
                new PKCS7Padding());
        cipher.reset();
        cipher.init(true, params);

        // write magic number
        out.write(MagicNumbers.PRIVATE_KEY);
        out.flush();

        // write initial vector and salt
        out.write(iv);
        out.write(salt);
        out.flush();

        // write encrypted key to output stream
        ByteArrayOutputStream buf = new ByteArrayOutputStream();
        CipherOutputStream cout = new CipherOutputStream(buf, cipher);
        cout.write(key);
        cout.close();
        out.write(buf.toByteArray());
        out.flush();

    } catch (UnsupportedEncodingException | NoSuchAlgorithmException ex) {

        throw new UnsupportedOperationException(ex.getMessage(), ex);
    }
}

From source file:net.nharyes.secrete.ecies.ECIES.java

License:Open Source License

private static IESEngine getIESEngine() {

    return new IESEngine(new Curve25519Agreement(), new KDF2BytesGenerator(new SHA512Digest()),
            new HMac(new SHA512Digest()),
            new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), new PKCS7Padding()));
}

From source file:net.sourceforge.keepassj2me.importerv3.ImporterV3.java

License:Open Source License

/**
 * Load a v3 database file, return contents in a new PwManager.
 * /*from ww w .j a  va2s . c o  m*/
 * @param infile  Existing file to load.
 * @param password Pass phrase for infile.
 * @param pRepair (unused)
 * @return new PwManager container.
 * 
 * @throws IOException on any file error.
 * @throws InvalidKeyException on a decryption error, or possible internal bug.
 * @throws IllegalBlockSizeException on a decryption error, or possible internal bug.
 * @throws BadPaddingException on a decryption error, or possible internal bug.
 * @throws NoSuchAlgorithmException on a decryption error, or possible internal bug.
 * @throws NoSuchPaddingException on a decryption error, or possible internal bug.
 * @throws InvalidAlgorithmParameterException if error decrypting main file body. 
 * @throws ShortBufferException if error decrypting main file body.
 */
public PwManager openDatabase(InputStream inStream, String password)
        throws IOException, InvalidCipherTextException, Exception {
    PwManager newManager;
    SHA256Digest md;
    /** Master key encrypted several times */
    byte[] transformedMasterKey;
    byte[] finalKey;

    setProgress(5, "Open database");
    // #ifdef DEBUG
    System.out.println("Open database");
    // #endif

    // Load entire file, most of it's encrypted.
    // InputStream in = new FileInputStream( infile );
    byte[] filebuf = new byte[(int) inStream.available()];
    inStream.read(filebuf, 0, (int) inStream.available());
    inStream.close();

    // Parse header (unencrypted)
    if (filebuf.length < PwDbHeader.BUF_SIZE)
        throw new IOException("File too short for header");
    PwDbHeader hdr = new PwDbHeader(filebuf, 0);

    if ((hdr.signature1 != PwManager.PWM_DBSIG_1) || (hdr.signature2 != PwManager.PWM_DBSIG_2)) {
        // #ifdef DEBUG
        System.out.println("Bad database file signature");
        // #endif
        throw new IOException("Bad database file signature");
    }

    if (hdr.version != PwManager.PWM_DBVER_DW) {
        // #ifdef DEBUG
        System.out.println("Bad database file version");
        // #endif
        throw new IOException("Bad database file version");
    }

    newManager = new PwManager();
    newManager.setMasterKey(password);

    // Select algorithm
    if ((hdr.flags & PwManager.PWM_FLAG_RIJNDAEL) != 0) {
        // #ifdef DEBUG
        System.out.println("Algorithm AES");
        // #endif
        newManager.algorithm = PwManager.ALGO_AES;
    } else if ((hdr.flags & PwManager.PWM_FLAG_TWOFISH) != 0) {
        // #ifdef DEBUG
        System.out.println("Algorithm TWOFISH");
        // #endif
        newManager.algorithm = PwManager.ALGO_TWOFISH;
    } else {
        throw new IOException("Unknown algorithm.");
    }

    if (newManager.algorithm == PwManager.ALGO_TWOFISH)
        throw new IOException("TwoFish algorithm is not supported");

    newManager.numKeyEncRounds = hdr.numKeyEncRounds;
    // #ifdef DEBUG
    System.out.println("rounds = " + newManager.numKeyEncRounds);
    // #endif

    // testRijndael_JCE();

    newManager.name = "KeePass Password Manager";

    // Generate transformedMasterKey from masterKey
    //KeePassMIDlet.logS ("masterSeed2: " + new String(Hex.encode(hdr.masterSeed2)));

    setProgress(10, "Decrypt key");
    transformedMasterKey = transformMasterKey(hdr.masterSeed2, newManager.masterKey,
            newManager.numKeyEncRounds);
    // Hash the master password with the salt in the file
    md = new SHA256Digest();
    md.update(hdr.masterSeed, 0, hdr.masterSeed.length);
    md.update(transformedMasterKey, 0, transformedMasterKey.length);
    finalKey = new byte[md.getDigestSize()];
    md.doFinal(finalKey, 0);

    setProgress(90, "Decrypt database");

    // NI
    //KeePassMIDlet.logS ("finalKey: " + new String(Hex.encode(finalKey)));

    // Initialize Rijndael algorithm

    // Cipher cipher = Cipher.getInstance( "AES/CBC/PKCS5Padding" );
    //PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()));
    BufferedBlockCipher cipher = new BufferedBlockCipher(new CBCBlockCipher(new AESEngine()));

    //cipher.init( Cipher.DECRYPT_MODE, new SecretKeySpec( finalKey, "AES" ), new IvParameterSpec( hdr.encryptionIV ) );

    cipher.init(false, new ParametersWithIV(new KeyParameter(finalKey), hdr.encryptionIV));
    // Decrypt! The first bytes aren't encrypted (that's the header)
    //int encryptedPartSize = cipher.doFinal( filebuf, PwDbHeader.BUF_SIZE, filebuf.length - PwDbHeader.BUF_SIZE, filebuf, PwDbHeader.BUF_SIZE );
    //int encryptedPartSize
    int paddedEncryptedPartSize = cipher.processBytes(filebuf, PwDbHeader.BUF_SIZE,
            filebuf.length - PwDbHeader.BUF_SIZE, filebuf, PwDbHeader.BUF_SIZE);

    int encryptedPartSize = 0;
    //try {
    PKCS7Padding padding = new PKCS7Padding();
    encryptedPartSize = paddedEncryptedPartSize - padding.padCount(filebuf);
    //} catch (Exception e) {
    //}
    // NI
    byte[] plainContent = new byte[encryptedPartSize];
    System.arraycopy(filebuf, PwDbHeader.BUF_SIZE, plainContent, 0, encryptedPartSize);
    // #ifdef DEBUG
    System.out.println("filebuf length: " + filebuf.length);
    // #endif
    //System.out.println ("file length: " + filebuf.length);
    //System.out.println ("plaintext contents length: " + encryptedPartSize);
    //System.out.println ("plaintext contents:\n" + new String(Hex.encode(plainContent)));

    //if( pRepair == null ) {
    //md = MessageDigest.getInstance( "SHA-256" );
    md = new SHA256Digest();
    md.update(filebuf, PwDbHeader.BUF_SIZE, encryptedPartSize);
    //      md.update( makePad(filebuf) );
    md.doFinal(finalKey, 0);

    if (Util.compare(finalKey, hdr.contentsHash) == false) {
        //KeePassMIDlet.logS ( "Database file did not decrypt correctly. (checksum code is broken)" );
        // #ifdef DEBUG
        System.out.println("Database file did not decrypt correctly. (checksum code is broken)");
        // #endif
        throw new Exception(
                "Wrong Password, or Database File Corrupted (database file did not decrypt correctly)");
    }
    // }

    setProgress(95, "Import groups");
    // Import all groups
    // #ifdef DEBUG
    System.out.println("Import all groups");
    // #endif

    int pos = PwDbHeader.BUF_SIZE;
    PwGroup newGrp = new PwGroup();
    for (int i = 0; i < hdr.numGroups;) {
        int fieldType = Types.readShort(filebuf, pos);
        pos += 2;
        int fieldSize = Types.readInt(filebuf, pos);
        pos += 4;

        if (fieldType == 0xFFFF) {
            // #ifdef DEBUG
            System.out.println(newGrp.level + " " + newGrp.name);
            // #endif

            // End-Group record.  Save group and count it.
            //newManager.groups.add( newGrp );
            newManager.addGroup(newGrp);
            newGrp = new PwGroup();
            i++;
        } else {
            readGroupField(newGrp, fieldType, filebuf, pos);
        }
        pos += fieldSize;
    }

    //    fixGroups( groups );

    setProgress(97, "Import entries");
    // Import all entries
    // #ifdef DEBUG
    System.out.println("Import all entries");
    // #endif

    PwEntry newEnt = new PwEntry();
    for (int i = 0; i < hdr.numEntries;) {
        int fieldType = Types.readShort(filebuf, pos);
        int fieldSize = Types.readInt(filebuf, pos + 2);

        if (fieldType == 0xFFFF) {
            // End-Group record.  Save group and count it.
            newManager.addEntry(newEnt);
            // #ifdef DEBUG
            System.out.println(newEnt.title);
            // #endif
            newEnt = new PwEntry();
            i++;
        } else {
            readEntryField(newEnt, filebuf, pos);
        }
        pos += 2 + 4 + fieldSize;
    }

    // Keep the Meta-Info entry separate
    // #ifdef DEBUG
    System.out.println("Keep the Meta-Info entry separate");
    // #endif

    for (int i = 0; i < newManager.entries.size(); i++) {
        PwEntry ent = (PwEntry) newManager.entries.elementAt(i);
        if (ent.title.equals("Meta-Info") && ent.url.equals("$") && ent.username.equals("SYSTEM")) {
            newManager.metaInfo = ent;
            newManager.entries.removeElementAt(i);
        }
    }

    setProgress(100, "Done");
    // #ifdef DEBUG
    System.out.println("Return newManager: " + newManager);
    // #endif

    return newManager;
}

From source file:net.sourceforge.keepassj2me.keydb.KeydbDatabase.java

License:Open Source License

/**
 * Encode database// ww w .j  a  v  a  2  s  .  c  o  m
 * @return encoded database
 * @throws KeydbException
 */
public byte[] getEncoded() throws KeydbException {//Encrypt content
    if (isLocked())
        return this.encodedContent;

    if ((this.header.numGroups == 0) && (this.header.numEntries == 0))
        throw new KeydbException(Config.getLocaleString(keys.KD_NOTHING_SAVE));

    BufferedBlockCipher cipher = new BufferedBlockCipher(new CBCBlockCipher(new AESEngine()));

    //calc padding size
    int block_size = cipher.getBlockSize();
    int pad_size = block_size - this.contentSize % block_size;

    // #ifdef DEBUG
    System.out.println("contentSize: " + this.contentSize);
    System.out.println("block_size: " + block_size);
    System.out.println("pad_size: " + pad_size);
    // #endif

    //add padding to content
    byte temp[] = new byte[this.contentSize + pad_size];
    System.arraycopy(this.plainContent, 0, temp, 0, this.contentSize);
    KeydbUtil.fill(this.plainContent, (byte) 0);
    this.plainContent = temp;
    temp = null;
    PKCS7Padding padding = new PKCS7Padding();
    padding.addPadding(this.plainContent, this.contentSize);

    byte encoded[] = new byte[KeydbHeader.SIZE + this.contentSize + pad_size];

    //encode
    cipher.init(true, new ParametersWithIV(new KeyParameter(this.key), this.header.encryptionIV));

    int paddedEncryptedPartSize = cipher.processBytes(this.plainContent, 0, this.plainContent.length, encoded,
            KeydbHeader.SIZE);

    if (paddedEncryptedPartSize != this.plainContent.length) {
        // #ifdef DEBUG
        System.out.println("Encoding: " + paddedEncryptedPartSize + " != " + this.plainContent.length);
        // #endif
        throw new KeydbException(Config.getLocaleString(keys.KD_ENCRYPTING_FAILED));
    }

    //Set header
    this.header.contentsHash = KeydbUtil.hash(this.plainContent, 0, this.contentSize);
    this.header.write(encoded, 0);

    return encoded;
}

From source file:net.sourceforge.keepassj2me.keydb.KeydbDatabase.java

License:Open Source License

private void decrypt(byte[] encoded, int offset, int length) throws KeydbException {
    BufferedBlockCipher cipher = new BufferedBlockCipher(new CBCBlockCipher(new AESEngine()));

    cipher.init(false, new ParametersWithIV(new KeyParameter(this.key), this.header.encryptionIV));

    // Decrypt! The first bytes aren't encrypted (that's the header)
    this.plainContent = new byte[encoded.length - KeydbHeader.SIZE];
    int paddedEncryptedPartSize = cipher.processBytes(encoded, offset, length, this.plainContent, 0);

    //detect padding and calc content size 
    this.contentSize = 0;
    PKCS7Padding padding = new PKCS7Padding();
    try {/*w  w  w  . j a va 2 s . co  m*/
        this.contentSize = paddedEncryptedPartSize - padding.padCount(this.plainContent);
    } catch (InvalidCipherTextException e) {
        throw new KeydbException(Config.getLocaleString(keys.KD_DB_DECRYPT_ERR, new String[] { "1" }));
    }

    if (!KeydbUtil.compare(KeydbUtil.hash(this.plainContent, 0, this.contentSize), this.header.contentsHash)) {
        throw new KeydbException(Config.getLocaleString(keys.KD_DB_DECRYPT_ERR, new String[] { "2" }));
    }
}

From source file:org.albertschmitt.crypto.AESService.java

License:Open Source License

/**
 * Return a PaddedBufferedBlockCipher for encryption or decryption.
 *
 * @param iv The initialization vector.//from ww  w  . ja v a 2 s.  c  om
 * @param forEncryption True to encrypt, false to decrypt.
 * @return PaddedBufferedBlockCipher configured to encrypt or decrypt.
 */
private PaddedBufferedBlockCipher getCipher(byte[] iv, Boolean forEncryption) {
    ParametersWithIV ivKeyParam = new ParametersWithIV(aes_key, iv);
    BlockCipherPadding padding = new PKCS7Padding();
    PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()),
            padding);
    cipher.reset();
    cipher.init(forEncryption, ivKeyParam);

    return cipher;
}

From source file:org.bunkr.core.utils.SimpleAES.java

License:Open Source License

private static byte[] runAES(Encryption encryptionAlgorithm, boolean doEncrypt, byte[] subject, byte[] key,
        byte[] iv) throws CryptoException {
    // set up padded buffered cipher
    PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(
            CipherBuilder.buildCipher(encryptionAlgorithm, doEncrypt, key, iv), new PKCS7Padding());

    // init with key and if
    cipher.init(doEncrypt, new ParametersWithIV(new KeyParameter(key), iv));

    // construct output buffer
    byte[] output = new byte[cipher.getOutputSize(subject.length)];

    // process all da bytes
    int cursor = cipher.processBytes(subject, 0, subject.length, output, 0);

    // process the last bytes from the buffer
    cipher.doFinal(output, cursor);/*from w ww  .j  ava  2s  . co  m*/
    return output;
}

From source file:org.cesecore.keys.token.BaseCryptoToken.java

License:Open Source License

/**
 * This method extracts a PrivateKey from the keystore and wraps it, using a symmetric encryption key
 *
 * @param privKeyTransform - transformation algorithm
 * @param spec - transformation algorithm spec (e.g: IvParameterSpec for CBC mode)
 * @param encryptionKeyAlias - alias of the symmetric key that will encrypt the private key
 * @param privateKeyAlias - alias for the PrivateKey to be extracted
 * @return byte[] with the encrypted extracted key
 * @throws NoSuchAlgorithmException if privKeyTransform is null, empty, in an invalid format, or if no Provider supports a CipherSpi
 *             implementation for the specified algorithm.
 * @throws NoSuchPaddingException if privKeyTransform contains a padding scheme that is not available.
 * @throws NoSuchProviderException if BouncyCastle is not registered in the security provider list.
 * @throws InvalidKeyException if the encryption key derived from encryptionKeyAlias was invalid.
 * @throws IllegalBlockSizeException if the Cipher created using privKeyTransform is a block cipher, no padding has been requested, and the length
 *             of the encoding of the key to be wrapped is not a multiple of the block size.
 * @throws CryptoTokenOfflineException if Crypto Token is not available or connected, or key with alias does not exist.
 * @throws InvalidAlgorithmParameterException if spec id not valid or supported.
 * @throws PrivateKeyNotExtractableException if the key is not extractable, does not exist or encryption fails
 */// ww  w  .  j a va 2  s  . c om
public byte[] extractKey(String privKeyTransform, AlgorithmParameterSpec spec, String encryptionKeyAlias,
        String privateKeyAlias) throws NoSuchAlgorithmException, NoSuchPaddingException,
        NoSuchProviderException, InvalidKeyException, IllegalBlockSizeException, CryptoTokenOfflineException,
        PrivateKeyNotExtractableException, InvalidAlgorithmParameterException {

    if (doPermitExtractablePrivateKey()) {
        // get encryption key
        Key encryptionKey = getKey(encryptionKeyAlias);
        // get private key to wrap
        PrivateKey privateKey = getPrivateKey(privateKeyAlias);
        if (privateKey == null) {
            throw new PrivateKeyNotExtractableException(
                    "Extracting key with alias '" + privateKeyAlias + "' return null.");
        }

        // since SUN PKCS11 Provider does not implements WRAP_MODE,
        // ENCRYPT_MODE with encoded private key will be used instead, giving the same result
        Cipher c = null;
        c = Cipher.getInstance(privKeyTransform, getEncProviderName());
        if (spec == null) {
            c.init(Cipher.ENCRYPT_MODE, encryptionKey);
        } else {
            c.init(Cipher.ENCRYPT_MODE, encryptionKey, spec);
        }

        // wrap key
        byte[] encryptedKey;
        try {
            byte[] data = privateKey.getEncoded();
            if (StringUtils.containsIgnoreCase(privKeyTransform, "NoPadding")) {
                // We must add PKCS7/PKCS5 padding ourselves to the data
                final PKCS7Padding padding = new PKCS7Padding();
                // Calculate the number of pad bytes needed
                final int rem = data.length % c.getBlockSize();
                final int padlen = c.getBlockSize() - rem;
                if (log.isDebugEnabled()) {
                    log.debug("Padding key data with " + padlen + " bytes, using PKCS7/5Padding. Total len: "
                            + (data.length + padlen));
                }
                byte[] newdata = Arrays.copyOf(data, data.length + padlen);
                padding.addPadding(newdata, data.length);
                data = newdata;
            }
            encryptedKey = c.doFinal(data);
        } catch (BadPaddingException e) {
            throw new PrivateKeyNotExtractableException(
                    "Extracting key with alias '" + privateKeyAlias + "' failed.");
        }

        return encryptedKey;
    } else {
        final String msg = intres.getLocalizedMessage("token.errornotextractable", privateKeyAlias,
                encryptionKeyAlias);
        throw new PrivateKeyNotExtractableException(msg);
    }
}

From source file:org.cryptacular.pbe.PBES2EncryptionScheme.java

License:Open Source License

/**
 * Initializes the block cipher and sets up its initialization parameters.
 *
 * @param  generator  Derived key generator.
 * @param  scheme  PKCS#5 encryption scheme.
 *//*  w  ww  . j  av  a2s  .  co m*/
private void initCipher(final PKCS5S2ParametersGenerator generator,
        final org.bouncycastle.asn1.pkcs.EncryptionScheme scheme) {
    final PBES2Algorithm alg = PBES2Algorithm.fromOid(scheme.getAlgorithm().getId());
    if (keyLength == 0) {
        keyLength = alg.getKeySize();
    }

    byte[] iv = null;
    CipherParameters cipherParameters = generator.generateDerivedParameters(keyLength);
    switch (alg) {

    case RC2:
        setCipher(alg.getCipherSpec().newInstance());

        final ASN1Sequence rc2Params = ASN1Sequence.getInstance(scheme.getParameters());
        if (rc2Params.size() > 1) {
            cipherParameters = new RC2Parameters(((KeyParameter) cipherParameters).getKey(),
                    ASN1Integer.getInstance(rc2Params.getObjectAt(0)).getValue().intValue());
            iv = ASN1OctetString.getInstance(rc2Params.getObjectAt(0)).getOctets();
        }
        break;

    case RC5:

        final ASN1Sequence rc5Params = ASN1Sequence.getInstance(scheme.getParameters());
        final int rounds = ASN1Integer.getInstance(rc5Params.getObjectAt(1)).getValue().intValue();
        final int blockSize = ASN1Integer.getInstance(rc5Params.getObjectAt(2)).getValue().intValue();
        if (blockSize == 32) {
            setCipher(new PaddedBufferedBlockCipher(new CBCBlockCipher(new RC532Engine()), new PKCS7Padding()));
        }
        cipherParameters = new RC5Parameters(((KeyParameter) cipherParameters).getKey(), rounds);
        if (rc5Params.size() > 3) {
            iv = ASN1OctetString.getInstance(rc5Params.getObjectAt(3)).getOctets();
        }
        break;

    default:
        setCipher(alg.getCipherSpec().newInstance());
        iv = ASN1OctetString.getInstance(scheme.getParameters()).getOctets();
    }
    if (iv != null) {
        cipherParameters = new ParametersWithIV(cipherParameters, iv);
    }
    setCipherParameters(cipherParameters);
}

From source file:org.cryptacular.spec.BufferedBlockCipherSpec.java

License:Open Source License

/**
 * Gets a instance of block cipher padding from a padding name string.
 *
 * @param  padding  Name of padding algorithm.
 *
 * @return  Block cipher padding instance.
 *//*from  www .  ja v  a 2 s. c om*/
private static BlockCipherPadding getPadding(final String padding) {
    final String name;
    final int pIndex = padding.indexOf("Padding");
    if (pIndex > -1) {
        name = padding.substring(0, pIndex);
    } else {
        name = padding;
    }

    BlockCipherPadding blockCipherPadding;
    if ("ISO7816d4".equalsIgnoreCase(name) | "ISO7816".equalsIgnoreCase(name)) {
        blockCipherPadding = new ISO7816d4Padding();
    } else if ("ISO10126".equalsIgnoreCase(name) || "ISO10126-2".equalsIgnoreCase(name)) {
        blockCipherPadding = new ISO10126d2Padding();
    } else if ("PKCS7".equalsIgnoreCase(name) || "PKCS5".equalsIgnoreCase(name)) {
        blockCipherPadding = new PKCS7Padding();
    } else if ("TBC".equalsIgnoreCase(name)) {
        blockCipherPadding = new TBCPadding();
    } else if ("X923".equalsIgnoreCase(name)) {
        blockCipherPadding = new X923Padding();
    } else if ("NULL".equalsIgnoreCase(name) || "Zero".equalsIgnoreCase(name)
            || "None".equalsIgnoreCase(name)) {
        blockCipherPadding = new ZeroBytePadding();
    } else {
        throw new IllegalArgumentException("Invalid padding " + padding);
    }
    return blockCipherPadding;
}