@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; }
/** * create a standard MAC based on a block cipher with the size of the * MAC been given in bits. This class uses CBC mode as the basis for the * MAC generation. * <p> * Note: the size of the MAC must be at least 24 bits (FIPS Publication 81), * or 16 bits if being used as a data authenticator (FIPS Publication 113), * and in general should be less than the size of the block cipher as it reduces * the chance of an exhaustive attack (see Handbook of Applied Cryptography). * * @param cipher the cipher to be used as the basis of the MAC generation. * @param macSizeInBits the size of the MAC in bits, must be a multiple of 8. * @param padding the padding to be used to complete the last block. */ public CBCBlockCipherMac( BlockCipher cipher, int macSizeInBits, BlockCipherPadding padding) { if ((macSizeInBits % 8) != 0) { throw new IllegalArgumentException("MAC size must be multiple of 8"); } this.cipher = new CBCBlockCipher(cipher); this.padding = padding; this.macSize = macSizeInBits / 8; mac = new byte[cipher.getBlockSize()]; buf = new byte[cipher.getBlockSize()]; bufOff = 0; }
/** * create a standard MAC based on a block cipher with the size of the * MAC been given in bits. This class uses CFB mode as the basis for the * MAC generation. * <p> * Note: the size of the MAC must be at least 24 bits (FIPS Publication 81), * or 16 bits if being used as a data authenticator (FIPS Publication 113), * and in general should be less than the size of the block cipher as it reduces * the chance of an exhaustive attack (see Handbook of Applied Cryptography). * * @param cipher the cipher to be used as the basis of the MAC generation. * @param cfbBitSize the size of an output block produced by the CFB mode. * @param macSizeInBits the size of the MAC in bits, must be a multiple of 8. * @param padding a padding to be used. */ public CFBBlockCipherMac( BlockCipher cipher, int cfbBitSize, int macSizeInBits, BlockCipherPadding padding) { if ((macSizeInBits % 8) != 0) { throw new IllegalArgumentException("MAC size must be multiple of 8"); } mac = new byte[cipher.getBlockSize()]; this.cipher = new MacCFBBlockCipher(cipher, cfbBitSize); this.padding = padding; this.macSize = macSizeInBits / 8; buf = new byte[this.cipher.getBlockSize()]; bufOff = 0; }
/** * create a standard MAC based on a block cipher with the size of the * MAC been given in bits. This class uses single DES CBC mode as the basis for the * MAC generation. The final block is decrypted and then encrypted using the * middle and right part of the key. * <p> * Note: the size of the MAC must be at least 24 bits (FIPS Publication 81), * or 16 bits if being used as a data authenticator (FIPS Publication 113), * and in general should be less than the size of the block cipher as it reduces * the chance of an exhaustive attack (see Handbook of Applied Cryptography). * * @param cipher the cipher to be used as the basis of the MAC generation. * @param macSizeInBits the size of the MAC in bits, must be a multiple of 8. * @param padding the padding to be used to complete the last block. */ public ISO9797Alg3Mac( BlockCipher cipher, int macSizeInBits, BlockCipherPadding padding) { if ((macSizeInBits % 8) != 0) { throw new IllegalArgumentException("MAC size must be multiple of 8"); } if (!(cipher instanceof DESEngine)) { throw new IllegalArgumentException("cipher must be instance of DESEngine"); } this.cipher = new CBCBlockCipher(cipher); this.padding = padding; this.macSize = macSizeInBits / 8; mac = new byte[cipher.getBlockSize()]; buf = new byte[cipher.getBlockSize()]; bufOff = 0; }
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); } }
public static BlockCipherEncryptor getEncryptor(String cipher, String mode, String padding) { StringBuilder sb = new StringBuilder(); sb.append(cipher).append("/").append(mode).append("/").append(padding); String type = sb.toString(); BlockCipherEncryptor bc = cache.get(type); if (bc == null) { BlockCipher engine = getBlockCipherEngine(cipher); BlockCipher modeEngine = wrapBlockCipherMode(engine, mode); BlockCipherPadding pad = getBlockCipherPadding(padding); BCBlockCipherBuilder builder = new BCBlockCipherBuilder(); builder.setBlockSize(engine.getBlockSize()).setKeySize(getKeySize(cipher)).setCipher(modeEngine) .setPadding(pad); bc = builder.build(); cache.put(type, bc); } return bc; }
private byte[] process(byte[] data, boolean encryption) throws DataLengthException { BlockCipher cipher = new AESEngine(); BlockCipherPadding padding = new ZeroBytePadding(); BufferedBlockCipher bufferedCipher = new PaddedBufferedBlockCipher(cipher, padding); bufferedCipher.init(encryption, key); byte[] output = new byte[bufferedCipher.getOutputSize(data.length)]; int bytesProcessed = bufferedCipher.processBytes(data, 0, data.length, output, 0); try { bufferedCipher.doFinal(output, bytesProcessed); return output; } catch (IllegalStateException | InvalidCipherTextException e) { e.printStackTrace(); } return null; }
/** * @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; }
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; }
private void blockCheck( PaddedBufferedBlockCipher cipher, BlockCipherPadding padding, KeyParameter key, byte[] data) { byte[] out = new byte[data.length + 8]; byte[] dec = new byte[data.length]; try { cipher.init(true, key); int len = cipher.processBytes(data, 0, data.length, out, 0); len += cipher.doFinal(out, len); cipher.init(false, key); int decLen = cipher.processBytes(out, 0, len, dec, 0); decLen += cipher.doFinal(dec, decLen); if (!areEqual(data, dec)) { fail("failed to decrypt - i = " + data.length + ", padding = " + padding.getPaddingName()); } } catch (Exception e) { fail("Exception - " + e.toString(), e); } }
/** * get the padding for an blockcipher * * @param paddingName * the name of the padding * @return the padding */ static BlockCipherPadding getBlockCipherPadding(String paddingName) { BlockCipherPadding padding = null; try { padding = blockCipherPadding.get(paddingName).newInstance(); return padding; } catch (InstantiationException | IllegalAccessException e) { throw new RuntimeException(e); } }
/** * get usable block cipher paddings * * @return names of usable block cipher paddings */ public static Set<String> getSupportedBlockCipherPadding() { Set<String> result = new TreeSet<>(); for (Entry<String, Class<? extends BlockCipherPadding>> iter : blockCipherPadding.entrySet()) { result.add(iter.getKey()); } return result; }
/** * Class constructor * * @param cipherMechanism block cipher mechanism identifier * @param paddingMechanism padding mechanism identifier * @param blockCipher block cipher object * @param padding padding object * @param key destroyable key * @param iv initial vector */ public CipherContext(final TypesProto.CipherMechanism cipherMechanism, final TypesProto.PaddingMechanism paddingMechanism, final BlockCipher blockCipher, final BlockCipherPadding padding, final DestroyableKey key, final byte[] iv) { if (Objects.isNull(cipherMechanism)) { throw new IllegalArgumentException("cipher mechanism is null"); } else if (Objects.isNull(padding)) { throw new IllegalArgumentException("padding mechanism is null"); } else if (Objects.isNull(blockCipher)) { throw new IllegalArgumentException("blockCipher is null"); } else if (Objects.isNull(padding)) { throw new IllegalArgumentException("padding is null"); } else if (Objects.isNull(key)) { throw new IllegalArgumentException("key is null"); } else if (ArrayUtils.isEmpty(iv)) { throw new IllegalArgumentException("iv is null/empty"); } this.cipherMechanism = cipherMechanism; this.paddingMechanism = paddingMechanism; this.blockCipher = blockCipher; this.padding = padding; this.key = key; this.iv = iv; this.streamCipher = null; }
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); }
private void registerBlockCipherPadding(final Class<? extends BlockCipherPadding> paddingClass) { final BlockCipherPadding padding = newInstance(paddingClass); final String paddingName = padding.getPaddingName(); logger.debug("registerBlockCipherPadding: paddingName=\"{}\" paddingClass=\"{}\"", paddingName, paddingClass.getName()); paddingName2blockCipherPaddingClass.put(paddingName.toUpperCase(Locale.ENGLISH), paddingClass); paddingName2blockCipherPaddingClass.put((paddingName + "Padding").toUpperCase(Locale.ENGLISH), paddingClass); }
private void registerBlockCipherPadding(final String paddingName, final Class<? extends BlockCipherPadding> paddingClass) { newInstance(paddingClass); // for testing to be sure there is a default constructor and we can call it. logger.trace("registerBlockCipherPadding: paddingName=\"{}\" paddingClass=\"{}\"", paddingName, paddingClass.getName()); paddingName2blockCipherPaddingClass.put(paddingName.toUpperCase(Locale.ENGLISH), paddingClass); paddingName2blockCipherPaddingClass.put((paddingName + "Padding").toUpperCase(Locale.ENGLISH), paddingClass); }
private BlockCipherPadding createBlockCipherPadding(final String paddingName) { final Class<? extends BlockCipherPadding> paddingClass = paddingName2blockCipherPaddingClass.get(paddingName); if (paddingClass == null) return null; return newInstance(paddingClass); }
private Cipher createCipherForBlockCipherMode(final String transformation, final BlockCipher modeWithEngine, final String engineName, final String modeName, final String paddingName) throws NoSuchPaddingException { if (paddingName.isEmpty() || "NOPADDING".equals(paddingName)) return new BufferedBlockCipherImpl(transformation, new BufferedBlockCipher(modeWithEngine)); final BlockCipherPadding padding = createBlockCipherPadding(paddingName); if (padding == null) throw new NoSuchPaddingException("There is no block-cipher-padding class registed with the name \"" + paddingName + "\"!"); return new BufferedBlockCipherImpl(transformation, new PaddedBufferedBlockCipher(modeWithEngine, padding)); }
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"); }
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; }