Java 类org.bouncycastle.crypto.paddings.PKCS7Padding 实例源码

项目:lastpass-java    文件:SimpleAesManaged.java   
@Override
    public String decrypt(byte[] encrypted) {
//        Cipher cipher = null;
        String plain;
        try {
//            Security.addProvider(new BouncyCastlePQCProvider());
//            cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", new BouncyCastlePQCProvider());
//            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(encryptionKey, "AES"), new IvParameterSpec(iv));
//            plain = new String(cipher.doFinal(encrypted), "UTF-8");
            KeyParameter keyParam = new KeyParameter(encryptionKey);
            CipherParameters params = new ParametersWithIV(keyParam, iv);
            BlockCipherPadding padding = new PKCS7Padding();
            BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(
                    new CBCBlockCipher(new AESEngine()), padding);
            cipher.reset();
            cipher.init(false, params);
            byte[] buffer = new byte[cipher.getOutputSize(encrypted.length)];
            int len = cipher.processBytes(encrypted, 0, encrypted.length, buffer, 0);
            len += cipher.doFinal(buffer, len);
            byte[] out = Arrays.copyOfRange(buffer, 0, len);
            plain = new String(out, "UTF-8");
        } catch (Exception e) {
            throw new RuntimeException("decrypt error in SimpleAesManaged", e);
        }
        return plain;
    }
项目:lastpass-java    文件:ParserHelperTest.java   
private static byte[] EncryptAes256(byte[] data, byte[] encryptionKey)
{
    try {
        KeyParameter keyParam = new KeyParameter(encryptionKey);
        BlockCipherPadding padding = new PKCS7Padding();
        BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(
                new CBCBlockCipher(new AESEngine()), padding);
        cipher.reset();
        cipher.init(true, keyParam);
        byte[] buffer = new byte[cipher.getOutputSize(data.length)];
        int len = cipher.processBytes(data, 0, data.length, buffer, 0);
        len += cipher.doFinal(buffer, len);
        return Arrays.copyOfRange(buffer, 0, len);
    } catch (Exception e) {
        throw new RuntimeException("decrypt error in SimpleAesManaged", e);
    }
}
项目:gwt-crypto    文件:SerpentTest.java   
private void doCbc(byte[] key, byte[] iv, byte[] pt, byte[] expected)
    throws Exception
{
    PaddedBufferedBlockCipher c = new PaddedBufferedBlockCipher(new CBCBlockCipher(new SerpentEngine()), new PKCS7Padding());

    byte[] ct = new byte[expected.length];

    c.init(true, new ParametersWithIV(new KeyParameter(key), iv));

    int l = c.processBytes(pt, 0, pt.length, ct, 0);

    c.doFinal(ct, l);

    if (!Arrays.areEqual(expected, ct))
    {
        fail("CBC test failed");
    }
}
项目:warp10-platform    文件:CryptoUtils.java   
public static byte[] wrap(byte[] key, byte[] data) {
  AESWrapEngine engine = new AESWrapEngine();
  KeyParameter params = new KeyParameter(key);
  engine.init(true, params);
  PKCS7Padding padding = new PKCS7Padding();
  byte[] unpadded = data;

  //
  // Add padding
  //

  byte[] padded = new byte[unpadded.length + (8 - unpadded.length % 8)];
  System.arraycopy(unpadded, 0, padded, 0, unpadded.length);
  padding.addPadding(padded, unpadded.length);

  //
  // Wrap
  //

  byte[] encrypted = engine.wrap(padded, 0, padded.length);

  return encrypted;
}
项目:java-security    文件:PasswordBasedEncryption.java   
/**
 * A password-based data decryption using a constant salt value "<b>constantSalt</b>"
 * @param cipher
 * @param password
 * @param salt
 * @param iterationCount
 * @return
 * @throws Exception
 */
public static byte[] decrypt(byte[] cipher, String password) throws Exception
{
    PKCS12ParametersGenerator pGen = new PKCS12ParametersGenerator(new SHA256Digest());
    char[] passwordChars = password.toCharArray();
    final byte[] pkcs12PasswordBytes = PBEParametersGenerator.PKCS12PasswordToBytes(passwordChars);
    pGen.init(pkcs12PasswordBytes, constantSalt.getBytes(), iterations);
    CBCBlockCipher aesCBC = new CBCBlockCipher(new AESEngine());
    ParametersWithIV aesCBCParams = (ParametersWithIV) pGen.generateDerivedParameters(256, 128);
    aesCBC.init(false, aesCBCParams);
    PaddedBufferedBlockCipher aesCipher = new PaddedBufferedBlockCipher(aesCBC, new PKCS7Padding());
    byte[] plainTemp = new byte[aesCipher.getOutputSize(cipher.length)];
    int offset = aesCipher.processBytes(cipher, 0, cipher.length, plainTemp, 0);
    int last = aesCipher.doFinal(plainTemp, offset);
    final byte[] plain = new byte[offset + last];
    System.arraycopy(plainTemp, 0, plain, 0, plain.length);
    return plain;
}
项目:bunkr    文件:SimpleBlockCipher.java   
private static byte[] operate(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);
    return output;
}
项目:jCryptTool    文件:AesEncryptionService.java   
@Override
public OutputStream encryptedOutputStream(final Path path, final String password) throws IOException,
        EncryptionFailedException {
    try {
        final byte[] salt = generateSalt();
        final byte[] key = generateKey(password, salt);
        final byte[] iv = generateIV();
        final byte[] fileInitBlock = generateOutputInitBlock(salt, iv);

        final PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(
                new CBCBlockCipher(new AESEngine()), new PKCS7Padding());

        final KeyParameter keyParam = new KeyParameter(key);
        final CipherParameters params = new ParametersWithIV(keyParam, iv);
        cipher.init(true, params);

        final BufferedOutputStream out = new BufferedOutputStream(Files.newOutputStream(path));
        out.write(fileInitBlock);

        return new CipherOutputStream(out, cipher);
    } catch (InvalidKeySpecException | NoSuchAlgorithmException e) {
        throw new EncryptionFailedException(e);
    }
}
项目:jCryptTool    文件:AesEncryptionService.java   
@Override
public InputStream decryptedInputStream(final Path path, final String password) throws IOException,
        DecryptionFailedException {
    try {
        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);
    }
}
项目:InflatableDonkey    文件:AESCBC.java   
public static byte[] decryptAESCBC(byte[] key, byte[] iv, byte[] data) {
    // AES CBC PKCS7 decrypt
    try {
        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);
    }
}
项目:kloudmake    文件:AESHelper.java   
private static byte[] crypt(final boolean encrypt, final byte[] bytes, final String password, final byte[] salt) throws InvalidCipherTextException {
    final PBEParametersGenerator keyGenerator = new PKCS12ParametersGenerator(new SHA256Digest());
    keyGenerator.init(PKCS12ParametersGenerator.PKCS12PasswordToBytes(password.toCharArray()), salt, 20);
    final CipherParameters keyParams = keyGenerator.generateDerivedParameters(256, 128);

    final BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), new PKCS7Padding());
    cipher.init(encrypt, keyParams);

    final byte[] processed = new byte[cipher.getOutputSize(bytes.length)];
    int outputLength = cipher.processBytes(bytes, 0, bytes.length, processed, 0);
    outputLength += cipher.doFinal(processed, outputLength);

    final byte[] results = new byte[outputLength];
    System.arraycopy(processed, 0, results, 0, outputLength);
    return results;
}
项目:MyDMAM    文件:Password.java   
/**
 * @return AES(BCrypt(clear_password, 10), SHA256(master_password_key))
 */
public byte[] getHashedPassword(String clear_password) throws SecurityException {
    String tested_password = testIfPasswordIsStrong(clear_password);
    try {
        byte[] hashed = (BCrypt.hashpw(tested_password, BCrypt.gensalt(10))).getBytes("UTF-8");

        BlockCipherPadding padding = new PKCS7Padding();
        BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), padding);
        cipher.reset();
        cipher.init(true, params);

        byte[] buf = new byte[cipher.getOutputSize(hashed.length)];
        int len = cipher.processBytes(hashed, 0, hashed.length, buf, 0);
        len += cipher.doFinal(buf, len);

        byte[] out = new byte[len];
        System.arraycopy(buf, 0, out, 0, len);

        return out;
    } catch (Exception e) {
        Loggers.Auth.error("Can't prepare password", e);
    }
    return null;
}
项目:MyDMAM    文件:Password.java   
public boolean checkPassword(String candidate_password, byte[] raw_password) {
    try {
        BlockCipherPadding padding = new PKCS7Padding();
        BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), padding);
        cipher.reset();
        cipher.init(false, params);

        byte[] buf = new byte[cipher.getOutputSize(raw_password.length)];
        int len = cipher.processBytes(raw_password, 0, raw_password.length, buf, 0);
        len += cipher.doFinal(buf, len);

        return BCrypt.checkpw(candidate_password, new String(buf, 0, len));
    } catch (Exception e) {
        Loggers.Auth.error("Can't extract hashed password", e);
    }
    return false;
}
项目:CryptoKnight    文件:Encryptor.java   
public void setParameters(int KeySize, int alg) throws NoSuchAlgorithmException, InvalidKeySpecException
{
    switch (alg)
    {
    case 7:
    case 1:
        this.blockSize = KeySize;
        break;

    case 8:
        this.blockSize = 256;
        break;

    default:
        this.blockSize = 128;
        break;
    }

    switch (KeySize)
    {
    case 128:
    case 192:
        Algs[1] = new RijndaelEngine(KeySize);
        break;

    case 256:
        Algs[1] = new RijndaelEngine(KeySize);
        Algs[7] = new ThreefishEngine(KeySize);
        break;

    default:
        Algs[7] = new ThreefishEngine(KeySize);
        break;
    }

    padding = new PKCS7Padding();       
}
项目:gwt-crypto    文件:PaddingTest.java   
private void testOutputSizes()
{
    PaddedBufferedBlockCipher bc = new PaddedBufferedBlockCipher(new DESEngine(), new PKCS7Padding());
    KeyParameter key = new KeyParameter(Hex.decode("0011223344556677"));

    for (int i = 0; i < bc.getBlockSize() * 2; i++)
    {
        bc.init(true, key);
        if (bc.getUpdateOutputSize(i) < 0)
        {
            fail("Padded cipher encrypt negative update output size for input size " + i);
        }
        if (bc.getOutputSize(i) < 0)
        {
            fail("Padded cipher encrypt negative output size for input size " + i);
        }

        bc.init(false, key);
        if (bc.getUpdateOutputSize(i) < 0)
        {
            fail("Padded cipher decrypt negative update output size for input size " + i);
        }
        if (bc.getOutputSize(i) < 0)
        {
            fail("Padded cipher decrypt negative output size for input size " + i);
        }

    }
}
项目:gwt-crypto    文件:CipherStreamTest.java   
private void testModes(BlockCipher cipher1, BlockCipher cipher2, int keySize)
    throws Exception
{
    final KeyParameter key = new KeyParameter(new byte[keySize]);
    final int blockSize = getBlockSize(cipher1);
    final CipherParameters withIv = new ParametersWithIV(key, new byte[blockSize]);

    if (blockSize > 1)
    {
        testMode(new PaddedBufferedBlockCipher(cipher1, new PKCS7Padding()), key);

        testMode(new PaddedBufferedBlockCipher(new CBCBlockCipher(cipher1), new PKCS7Padding()), withIv);

        testMode(new BufferedBlockCipher(new OFBBlockCipher(cipher1, blockSize)), withIv);
        testMode(new BufferedBlockCipher(new CFBBlockCipher(cipher1, blockSize)), withIv);
        testMode(new BufferedBlockCipher(new SICBlockCipher(cipher1)), withIv);
    }
    // CTS requires at least one block
    if (blockSize <= 16 && streamSize >= blockSize)
    {
        testMode(new CTSBlockCipher(cipher1), key);
    }
    if (blockSize <= 16 && streamSize >= blockSize)
    {
        testMode(new NISTCTSBlockCipher(NISTCTSBlockCipher.CS1, cipher1), key);
        testMode(new NISTCTSBlockCipher(NISTCTSBlockCipher.CS2, cipher1), key);
        testMode(new NISTCTSBlockCipher(NISTCTSBlockCipher.CS3, cipher1), key);
    }
    if (blockSize == 8 || blockSize == 16)
    {
        testMode(new EAXBlockCipher(cipher1), withIv);
    }
    if (blockSize == 16)
    {
        testMode(new CCMBlockCipher(cipher1), new ParametersWithIV(key, new byte[7]));
        testMode(new GCMBlockCipher(cipher1), withIv);
        testMode(new OCBBlockCipher(cipher1, cipher2), new ParametersWithIV(key, new byte[15]));
    }
}
项目:vsDiaryWriter    文件:BlockCiphers.java   
private static void initBlockCipherPaddings() {
    blockCipherPadding.put("ISO10126d2Padding", ISO10126d2Padding.class);
    blockCipherPadding.put("ISO7816d4Padding", ISO7816d4Padding.class);
    blockCipherPadding.put("PKCS7Padding", PKCS7Padding.class);
    blockCipherPadding.put("TBCPadding", TBCPadding.class);
    blockCipherPadding.put("X923Padding", X923Padding.class);
    blockCipherPadding.put("ZeroBytePadding", ZeroBytePadding.class);
}
项目:photon-model    文件:EncryptorService.java   
private BufferedBlockCipher getCipher(boolean forEncryption) {
    BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(
            new CBCBlockCipher(new AESEngine()), new PKCS7Padding());
    cipher.init(forEncryption, new ParametersWithIV(new KeyParameter(this.keyBytes, IV_LENGTH,
            this.keyBytes.length - IV_LENGTH), this.keyBytes, 0, IV_LENGTH));
    return cipher;
}
项目:warp10-platform    文件:CryptoUtils.java   
public static byte[] unwrap(byte[] key, byte[] data) {
  //
  // Decrypt the encrypted data
  //

  AESWrapEngine engine = new AESWrapEngine();
  CipherParameters params = new KeyParameter(key);
  engine.init(false, params);

  try {
    byte[] decrypted = engine.unwrap(data, 0, data.length);
    //
    // Unpad the decrypted data
    //

    PKCS7Padding padding = new PKCS7Padding();
    int padcount = padding.padCount(decrypted);

    //
    // Remove padding
    //

    decrypted = Arrays.copyOfRange(decrypted, 0, decrypted.length - padcount);

    return decrypted;
  } catch (InvalidCipherTextException icte) {
    return null;
  }
}
项目:cosigner    文件:Aes.java   
private static String transform(byte[] key, byte[] iv, String encString, boolean encrypt)
    throws Exception {

  // setup cipher parameters with key and IV
  KeyParameter keyParam = new KeyParameter(key);
  CipherParameters params = new ParametersWithIV(keyParam, iv);

  // setup AES cipher in CBC mode with PKCS7 padding
  BlockCipherPadding padding = new PKCS7Padding();
  BufferedBlockCipher cipher =
      new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), padding);
  cipher.reset();
  cipher.init(encrypt, params);

  // create a temporary buffer to decode into (it'll include padding)
  byte[] encData = ByteUtilities.toByteArray(encString);
  byte[] buf = new byte[cipher.getOutputSize(encData.length)];
  int len = cipher.processBytes(encData, 0, encData.length, buf, 0);
  len += cipher.doFinal(buf, len);

  // remove padding
  byte[] out = new byte[len];
  System.arraycopy(buf, 0, out, 0, len);

  // return string representation of decoded bytes
  return ByteUtilities.toHexString(out);
}
项目:secrete    文件:Curve25519PrivateKey.java   
public static Curve25519PrivateKey deserialize(InputStream in, char[] password) throws IOException {

        try {

            // check magic number
            byte[] mn = new byte[MagicNumbers.PRIVATE_KEY.length];
            IOUtils.readFully(in, mn, 0, mn.length);
            if (!Arrays.areEqual(mn, MagicNumbers.PRIVATE_KEY))
                throw new IllegalArgumentException("Wrong key file format");

            // read initial vector
            byte[] iv = new byte[16];
            IOUtils.readFully(in, iv, 0, iv.length);

            // read salt
            byte[] salt = new byte[64];
            IOUtils.readFully(in, salt, 0, salt.length);

            // 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(false, params);

            // decrypt key
            CipherInputStream cin = new CipherInputStream(in, cipher);
            byte[] key = new byte[Curve25519.KEY_SIZE];
            IOUtils.readFully(cin, key, 0, key.length);

            // return key instance
            return new Curve25519PrivateKey(key);

        } catch (UnsupportedEncodingException ex) {

            throw new UnsupportedOperationException(ex.getMessage(), ex);
        }
    }
项目:inbot-utils    文件:AESUtils.java   
private static String encryptBouncyCastle(SecretKey secret, String plainText) {
    try {
        // prepending with md5 hash allows us to do an integrity check on decrypt to prevent returning garbage if the decrypt key is incorrect
        String md5 = HashUtils.md5(plainText);
        plainText = md5 + plainText;

        // the iv acts as a per use salt, this ensures things encrypted with the same key always have a unique salt
        // 128 bit iv because NIST AES is standardized with 128 bit blocks and iv needs to match block size, even when using 256 bit key
        byte[] iv = new byte[16];
        SECURE_RANDOM.nextBytes(iv);

        // setup cipher parameters with key and IV
        byte[] key = secret.getEncoded();


        // setup AES cipher in CBC mode with PKCS7 padding
        BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), new PKCS7Padding());

        cipher.reset();
        cipher.init(true, new ParametersWithIV(new KeyParameter(key), iv));

        byte[] plainTextBuf = plainText.getBytes(StandardCharsets.UTF_8);

        byte[] buf = new byte[cipher.getOutputSize(plainTextBuf.length)];

        int len = cipher.processBytes(plainTextBuf, 0, plainTextBuf.length, buf, 0);
        len += cipher.doFinal(buf, len);

        // copy the encrypted part of the buffer to out
        byte[] out = new byte[len];
        System.arraycopy(buf, 0, out, 0, len);

        // iv$encrypted
        return byteArrayToHexString(iv) + "$" + new String(Base64.encodeBase64URLSafe(out), StandardCharsets.UTF_8);
    } catch (DataLengthException | InvalidCipherTextException e) {
        throw new IllegalStateException("cannot encrypt", e);
    }
}
项目:jCryptTool    文件:AesEncryptionService.java   
@Override
public String encryptString(final String string, final String password) throws EncryptionFailedException {
    try {
        final byte[] salt = generateSalt();
        final byte[] key = generateKey(password, salt);
        final byte[] iv = generateIV();
        final byte[] outputInitBlock = generateOutputInitBlock(salt, iv);

        final PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(
                new CBCBlockCipher(new AESEngine()), new PKCS7Padding());

        final KeyParameter keyParam = new KeyParameter(key);
        final CipherParameters params = new ParametersWithIV(keyParam, iv);
        cipher.init(true, params);

        final byte in[] = string.getBytes();
        final byte out[] = new byte[cipher.getOutputSize(in.length)];
        final int len1 = cipher.processBytes(in, 0, in.length, out, 0);

        cipher.doFinal(out, len1);

        final byte[] result = Arrays.concatenate(outputInitBlock, out);

        return Base64.toBase64String(result);
    } catch (InvalidKeySpecException | NoSuchAlgorithmException | InvalidCipherTextException e) {
        throw new EncryptionFailedException(e);
    }
}
项目:scs-lib    文件:SimpleCryptoService.java   
public void init(final String base64Iv, final byte[] encKey, final byte[] hmacKey) {
    iv = Base64.decodeBase64(base64Iv);
    cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), new PKCS7Padding());
    encKeyParam = new KeyParameter(encKey);
    mac = new HMac(new SHA1Digest());
    mac.init(new KeyParameter(hmacKey));
}
项目:CryptMeme    文件:AbstractCryptoImplementation.java   
protected byte[] encryptAes(byte[] data, byte[] key, byte[] iv) {
    // pad the data
    int unpaddedLength = data.length;
    data = Arrays.copyOf(data, unpaddedLength + BLOCK_SIZE - unpaddedLength%BLOCK_SIZE);  // make data.length a multiple of BLOCK_SIZE; if the length is a multiple of BLOCK_LENGTH, add a block of zeros
    PKCS7Padding padding = new PKCS7Padding();
    int numAdded = padding.addPadding(data, unpaddedLength);
    if (log.shouldLog(Log.DEBUG) && numAdded != BLOCK_SIZE-unpaddedLength%BLOCK_SIZE)
        log.error("Error: " + numAdded + " pad bytes added, expected: " + (BLOCK_SIZE-unpaddedLength%BLOCK_SIZE));

    byte[] encryptedData = new byte[data.length];
    SessionKey sessionKey = new SessionKey(key);
    appContext.aes().encrypt(data, 0, encryptedData, 0, sessionKey, iv, data.length);   // this method also checks that data.length is divisible by 16
    return encryptedData;
}
项目:CryptMeme    文件:AbstractCryptoImplementation.java   
protected byte[] decryptAes(byte[] data, byte[] key, byte[] iv) throws InvalidCipherTextException {
    SessionKey sessionKey = new SessionKey(key);
    byte[] decryptedData = new byte[data.length];
    if (data.length%BLOCK_SIZE != 0)
        log.error("Length of encrypted data is not divisible by " + BLOCK_SIZE + ". Length=" + decryptedData.length);
    appContext.aes().decrypt(data, 0, decryptedData, 0, sessionKey, iv, data.length);

    // unpad the decrypted data
    byte[] lastBlock = Arrays.copyOfRange(decryptedData, decryptedData.length-iv.length, decryptedData.length);
    PKCS7Padding padding = new PKCS7Padding();
    int padCount = padding.padCount(lastBlock);
    decryptedData = Arrays.copyOf(decryptedData, decryptedData.length-padCount);

    return decryptedData;
}
项目:geowave    文件:GeoWaveEncryption.java   
private PaddedBufferedBlockCipher getCipher(
        boolean encrypt ) {
    PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(
            new CBCBlockCipher(
                    new AESEngine()),
            new PKCS7Padding());
    CipherParameters ivAndKey = new ParametersWithIV(
            new KeyParameter(
                    getKey().getEncoded()),
            salt);
    cipher.init(
            encrypt,
            ivAndKey);
    return cipher;
}
项目:jlubricant    文件:VerifiedTextEncryptor.java   
public static String dec(String password, String salt, String encString)
        throws Exception {

    byte[] ivData = toByte(encString.substring(0, 32));
    byte[] encData = toByte(encString.substring(32));

    // get raw key from password and salt
    PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray(),
            toByte(salt), 50, 256);
    SecretKeyFactory keyFactory = SecretKeyFactory
            .getInstance("PBEWithSHA256And256BitAES-CBC-BC");
    SecretKeySpec secretKey = new SecretKeySpec(keyFactory.generateSecret(
            pbeKeySpec).getEncoded(), "AES");
    byte[] key = secretKey.getEncoded();

    // setup cipher parameters with key and IV
    KeyParameter keyParam = new KeyParameter(key);
    CipherParameters params = new ParametersWithIV(keyParam, ivData);

    // setup AES cipher in CBC mode with PKCS7 padding
    BlockCipherPadding padding = new PKCS7Padding();
    BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(
            new CBCBlockCipher(new AESEngine()), padding);
    cipher.reset();
    cipher.init(false, params);

    // create a temporary buffer to decode into (it'll include padding)
    byte[] buf = new byte[cipher.getOutputSize(encData.length)];
    int len = cipher.processBytes(encData, 0, encData.length, buf, 0);
    len += cipher.doFinal(buf, len);

    // remove padding
    byte[] out = new byte[len];
    System.arraycopy(buf, 0, out, 0, len);

    // return string representation of decoded bytes
    return new String(out, "UTF-8");
}
项目:MyDMAM    文件:Protocol.java   
private byte[] encryptDecrypt(byte[] datas, int pos, int len, int mode) throws GeneralSecurityException, DataLengthException, IllegalStateException, InvalidCipherTextException {
    if (log.isTraceEnabled()) {
        if (mode == Cipher.ENCRYPT_MODE) {
            log.trace("Raw data input (no crypted)" + Hexview.LINESEPARATOR + Hexview.tracelog(datas, pos, len));
        } else {
            log.trace("Raw data input (crypted)" + Hexview.LINESEPARATOR + Hexview.tracelog(datas, pos, len));
        }
    }

    BlockCipherPadding padding = new PKCS7Padding();
    BufferedBlockCipher cipher2 = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), padding);
    cipher2.reset();
    cipher2.init(mode == Cipher.ENCRYPT_MODE, params);

    byte[] buf = new byte[cipher2.getOutputSize(len)];
    int len2 = cipher2.processBytes(datas, pos, len, buf, 0);
    len2 += cipher2.doFinal(buf, len2);

    byte[] result = new byte[len2];
    System.arraycopy(buf, 0, result, 0, len2);

    if (log.isTraceEnabled()) {
        if (mode == Cipher.ENCRYPT_MODE) {
            log.trace("Raw data input (crypted)" + Hexview.LINESEPARATOR + Hexview.tracelog(result, 0, result.length));
        } else {
            log.trace("Raw data input (decrypted)" + Hexview.LINESEPARATOR + Hexview.tracelog(result, 0, result.length));
        }
    }
    return result;
}
项目:ipack    文件:BcPKCS12PBEOutputEncryptorBuilder.java   
public BcPKCS12PBEOutputEncryptorBuilder(ASN1ObjectIdentifier algorithm, BlockCipher engine, ExtendedDigest pbeDigest)
{
    this.algorithm = algorithm;
    this.engine = new PaddedBufferedBlockCipher(engine, new PKCS7Padding());
    this.digest = pbeDigest;
}
项目:gwt-crypto    文件:BcPKCS12PBEOutputEncryptorBuilder.java   
public BcPKCS12PBEOutputEncryptorBuilder(ASN1ObjectIdentifier algorithm, BlockCipher engine, ExtendedDigest pbeDigest)
{
    this.algorithm = algorithm;
    this.engine = new PaddedBufferedBlockCipher(engine, new PKCS7Padding());
    this.digest = pbeDigest;
}
项目:gwt-crypto    文件:PaddingTest.java   
public void performTest()
{
    SecureRandom    rand = new SecureRandom(new byte[20]);

    rand.setSeed(System.currentTimeMillis());

    testPadding(new PKCS7Padding(), rand,
                                Hex.decode("ffffff0505050505"),
                                Hex.decode("0000000004040404"));

    PKCS7Padding padder = new PKCS7Padding();
    try
    {
        padder.padCount(new byte[8]);

        fail("invalid padding not detected");
    }
    catch (InvalidCipherTextException e)
    {
        if (!"pad block corrupted".equals(e.getMessage()))
        {
            fail("wrong exception for corrupt padding: " + e);
        }
    } 

    testPadding(new ISO10126d2Padding(), rand,
                                null,
                                null);

    testPadding(new X923Padding(), rand,
                                null,
                                null);

    testPadding(new TBCPadding(), rand,
                                Hex.decode("ffffff0000000000"),
                                Hex.decode("00000000ffffffff"));

    testPadding(new ZeroBytePadding(), rand,
                                Hex.decode("ffffff0000000000"),
                                null);

    testPadding(new ISO7816d4Padding(), rand,
                                Hex.decode("ffffff8000000000"),
                                Hex.decode("0000000080000000"));

    testOutputSizes();

}
项目:warp10-platform    文件:GTSEncoder.java   
/**
 * Return the bytes currently in this encoder.
 * If 'wrappingKey' is non null, encrypt the bytes prior to returning them.
 * 
 * @return The (possibly encrypted bytes) or null if an exception is raised
 *         while encrypting.
 * 
 */
public byte[] getBytes() {
  if (null == this.wrappingKey) {
    return this.stream.toByteArray();
  } else {
    AESWrapEngine engine = new AESWrapEngine();
    KeyParameter params = new KeyParameter(this.wrappingKey);
    engine.init(true, params);
    PKCS7Padding padding = new PKCS7Padding();
    byte[] unpadded = this.stream.toByteArray();

    //
    // Add padding
    //

    byte[] padded = new byte[unpadded.length + (8 - unpadded.length % 8)];
    System.arraycopy(unpadded, 0, padded, 0, unpadded.length);
    padding.addPadding(padded, unpadded.length);

    //
    // Wrap
    //

    byte[] encrypted = engine.wrap(padded, 0, padded.length);

    //
    // Add 0x0 flag and encrypted data size
    //

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    try {
      baos.write(GTSEncoder.FLAGS_ENCRYPTED);
      baos.write(Varint.encodeUnsignedLong(encrypted.length));
      baos.write(encrypted);
      return baos.toByteArray();
    } catch (IOException ioe) {
      return null;
    }
  }
}
项目:warp10-platform    文件:GTSEncoderTest.java   
@Test
public void testAddValue_encrypted() throws Exception {
  long now = System.currentTimeMillis() * 1000L;

  byte[] key = new byte[32];

  GTSEncoder encoder = new GTSEncoder(now - 1000000L, key);

  encoder.addValue(now, GeoTimeSerie.NO_LOCATION, GeoTimeSerie.NO_ELEVATION, 1L);
  encoder.addValue(now + 1000000L, GeoTimeSerie.NO_LOCATION, GeoTimeSerie.NO_ELEVATION, 2L);

  byte[] encrypted = encoder.getBytes();
  Assert.assertEquals(GTSEncoder.FLAGS_ENCRYPTED, encrypted[0] & GTSEncoder.FLAGS_MASK_ENCRYPTED);
  Assert.assertEquals(26, encrypted.length);

  //
  // Now check that we can decrypt the payload
  // We can't use n offset different than 0 in unwrap due to BJA-461
  // so we have to copy the data prior to decrypting it.
  //

  AESWrapEngine engine = new AESWrapEngine();
  KeyParameter params = new KeyParameter(key);
  engine.init(false, params);
  byte[] enc = new byte[24];
  System.arraycopy(encrypted, 2, enc, 0, 24);
  byte[] decrypted = engine.unwrap(enc, 0, 24);    

  //
  // Now decode the decrypted data
  //

  PKCS7Padding padding = new PKCS7Padding();    
  GTSDecoder decoder = new GTSDecoder(now - 1000000L, ByteBuffer.wrap(decrypted, 0, decrypted.length - padding.padCount(decrypted)));

  decoder.next();
  Assert.assertEquals(now, decoder.getTimestamp());
  Assert.assertEquals(GeoTimeSerie.NO_LOCATION, decoder.getLocation());
  Assert.assertEquals(GeoTimeSerie.NO_ELEVATION, decoder.getElevation());
  Assert.assertEquals(1L, decoder.getValue());

  decoder.next();
  Assert.assertEquals(now + 1000000L, decoder.getTimestamp());
  Assert.assertEquals(GeoTimeSerie.NO_LOCATION, decoder.getLocation());
  Assert.assertEquals(GeoTimeSerie.NO_ELEVATION, decoder.getElevation());
  Assert.assertEquals(2L, decoder.getValue());
}
项目:Aki-SSL    文件:BcPKCS12PBEOutputEncryptorBuilder.java   
public BcPKCS12PBEOutputEncryptorBuilder(ASN1ObjectIdentifier algorithm, BlockCipher engine, ExtendedDigest pbeDigest)
{
    this.algorithm = algorithm;
    this.engine = new PaddedBufferedBlockCipher(engine, new PKCS7Padding());
    this.digest = pbeDigest;
}
项目:secrete    文件:Curve25519PrivateKey.java   
public void serialize(OutputStream out, char[] password) throws IOException {

        try {

            // 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);
        }
    }
项目:Raven-Messenger    文件:ThreefishBouncyCastle.java   
public static byte[] encrypt(byte[] key, byte[] input) throws DataLengthException, InvalidCipherTextException {
    pbbc = new PaddedBufferedBlockCipher(ThreefishCipher, new PKCS7Padding());
    ThreefishBouncyCastle.key = new KeyParameter(key);
    return processing(input, true);
}
项目:Raven-Messenger    文件:ThreefishBouncyCastle.java   
public static byte[] decrypt(byte[] key, byte[] input) throws DataLengthException, InvalidCipherTextException {
    pbbc = new PaddedBufferedBlockCipher(ThreefishCipher, new PKCS7Padding());
    ThreefishBouncyCastle.key = new KeyParameter(key);
    return processing(input, false);
}
项目:Raven-Messenger    文件:AESBouncyCastle.java   
public static byte[] encrypt(byte[] key, byte[] input) throws DataLengthException, InvalidCipherTextException {
    pbbc = new PaddedBufferedBlockCipher(AESCipher, new PKCS7Padding());
    AESBouncyCastle.key = new KeyParameter(key);
    return processing(input, true);
}
项目:Raven-Messenger    文件:AESBouncyCastle.java   
public static byte[] decrypt(byte[] key, byte[] input) throws DataLengthException, InvalidCipherTextException {
    pbbc = new PaddedBufferedBlockCipher(AESCipher, new PKCS7Padding());
    AESBouncyCastle.key = new KeyParameter(key);
    return processing(input, false);
}
项目:irma_future_id    文件:BcPKCS12PBEOutputEncryptorBuilder.java   
public BcPKCS12PBEOutputEncryptorBuilder(ASN1ObjectIdentifier algorithm, BlockCipher engine, ExtendedDigest pbeDigest)
{
    this.algorithm = algorithm;
    this.engine = new PaddedBufferedBlockCipher(engine, new PKCS7Padding());
    this.digest = pbeDigest;
}