org.bouncycastle.crypto.modes.CBCBlockCipher Java Examples

The following examples show how to use org.bouncycastle.crypto.modes.CBCBlockCipher. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SecurityHandler.java    From sambox with Apache License 2.0 7 votes vote down vote up
/**
 * Encrypt or decrypt data with AES256.
 *
 * @param data The data to encrypt.
 * @param output The output to write the encrypted data to.
 *
 * @throws IOException If there is an error reading the data.
 */
private void decryptDataAES256(InputStream data, OutputStream output) throws IOException
{
    byte[] iv = new byte[16];

    // read IV from stream
    int ivSize = data.read(iv);
    if (ivSize == -1)
    {
        return;
    }

    if (ivSize != iv.length)
    {
        throw new IOException("AES initialization vector not fully read: only " + ivSize
                + " bytes read instead of " + iv.length);
    }
    PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(
            new CBCBlockCipher(new AESFastEngine()));
    cipher.init(false, new ParametersWithIV(new KeyParameter(encryptionKey), iv));
    try (CipherInputStream cis = new CipherInputStream(data, cipher))
    {
        IOUtils.copy(cis, output);
    }
}
 
Example #2
Source File: CmsCryptoDES.java    From oneops with Apache License 2.0 6 votes vote down vote up
/**
 * Encrypt.
 *
 * @param instr the instr
 * @return the string
 * @throws java.security.GeneralSecurityException the general security exception
 */
@Override
public String encrypt(String instr) throws GeneralSecurityException {
    long t1 = System.currentTimeMillis();
    byte[] in = instr.getBytes();
    PaddedBufferedBlockCipher encryptor = new PaddedBufferedBlockCipher(
            new CBCBlockCipher(new DESedeEngine()));
    encryptor.init(true, keyParameter);
    byte[] cipherText = new byte[encryptor.getOutputSize(in.length)];
    int outputLen = encryptor.processBytes(in, 0, in.length, cipherText, 0);
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {
        encryptor.doFinal(cipherText, outputLen);
        Hex.encode(cipherText, os);
    } catch (Exception e) {
        e.printStackTrace();
        throw new GeneralSecurityException(e);
    }
    long t2 = System.currentTimeMillis();
    logger.debug("Time taken to encrypt(millis) :" + (t2 - t1));
    return ENC_PREFIX + os.toString();
}
 
Example #3
Source File: AESCBC.java    From InflatableDonkey with MIT License 6 votes vote down vote up
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);
    }
}
 
Example #4
Source File: Metodos.java    From ExamplesAndroid with Apache License 2.0 6 votes vote down vote up
public String testEncryptRijndael(String value,String key) throws DataLengthException, IllegalStateException, InvalidCipherTextException {
    BlockCipher engine = new RijndaelEngine(256);
    BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(engine), new ZeroBytePadding());

    byte[] keyBytes = key.getBytes();
    cipher.init(true, new KeyParameter(keyBytes));

    byte[] input = value.getBytes();
    byte[] cipherText = new byte[cipher.getOutputSize(input.length)];

    int cipherLength = cipher.processBytes(input, 0, input.length, cipherText, 0);
    cipher.doFinal(cipherText, cipherLength);

    String result = new String(Base64.encode(cipherText));
    //Log.e("testEncryptRijndael : " , result);
    return  result;
}
 
Example #5
Source File: UploadEncryptFileController.java    From Spring-MVC-Blueprints with MIT License 6 votes vote down vote up
private byte[] encryptDESFile(String keys, byte[] plainText) {
BlockCipher engine = new DESEngine();

      byte[] key = keys.getBytes();
      byte[] ptBytes = plainText;
      BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(engine));
      cipher.init(true, new KeyParameter(key));
      byte[] rv = new byte[cipher.getOutputSize(ptBytes.length)];
      int tam = cipher.processBytes(ptBytes, 0, ptBytes.length, rv, 0);
      try {
          cipher.doFinal(rv, tam);
      } catch (Exception ce) {
          ce.printStackTrace();
      }
      return rv;
  }
 
Example #6
Source File: DESEncrypter.java    From gocd with Apache License 2.0 6 votes vote down vote up
private static String decrypt(byte[] key, String cipherText) throws CryptoException {
    try {
        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new DESEngine()));
        cipher.init(false, new KeyParameter(key));
        byte[] cipherTextBytes = DECODER.decode(cipherText);

        byte[] plainTextBytes = new byte[cipher.getOutputSize(cipherTextBytes.length)];
        int outputLength = cipher.processBytes(cipherTextBytes, 0, cipherTextBytes.length, plainTextBytes, 0);
        cipher.doFinal(plainTextBytes, outputLength);
        int paddingStarts = plainTextBytes.length - 1;
        for (; paddingStarts >= 0; paddingStarts--) {
            if (plainTextBytes[paddingStarts] != 0) {
                break;
            }
        }
        return new String(plainTextBytes, 0, paddingStarts + 1);
    } catch (Exception e) {
        throw new CryptoException(e);
    }
}
 
Example #7
Source File: CmsCryptoDES.java    From oneops with Apache License 2.0 6 votes vote down vote up
private String decryptStr(String instr) throws GeneralSecurityException {
    if(StringUtils.isEmpty(instr)){
        return instr;
    }
    long t1 = System.currentTimeMillis();
    PaddedBufferedBlockCipher decryptor = new PaddedBufferedBlockCipher(
            new CBCBlockCipher(new DESedeEngine()));
    decryptor.init(false, keyParameter);
    byte[] in = null;
    byte[] cipherText = null;

    try {
    	in = Hex.decode(instr);
    	cipherText = new byte[decryptor.getOutputSize(in.length)];

     int outputLen = decryptor.processBytes(in, 0, in.length, cipherText, 0);
        decryptor.doFinal(cipherText, outputLen);
    } catch (Exception e) {
        throw new GeneralSecurityException(e);
    }
    long t2 = System.currentTimeMillis();
    logger.debug("Time taken to decrypt(millis) : " + (t2 - t1));
    return (new String(cipherText)).replaceAll("\\u0000+$", "");
}
 
Example #8
Source File: AESEncrypt.java    From nuls-v2 with MIT License 6 votes vote down vote up
/**
 * 数据通过KeyParameter解密
 *
 * @param dataToDecrypt 需要解密的数据
 * @param aesKey        秘钥
 * @return 解密后的数据
 */
public static byte[] decrypt(EncryptedData dataToDecrypt, KeyParameter aesKey) throws CryptoException {
    HexUtil.checkNotNull(dataToDecrypt);
    HexUtil.checkNotNull(aesKey);

    try {
        ParametersWithIV keyWithIv = new ParametersWithIV(new KeyParameter(aesKey.getKey()), dataToDecrypt.getInitialisationVector());

        // Decrypt the validator.
        BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));
        cipher.init(false, keyWithIv);

        byte[] cipherBytes = dataToDecrypt.getEncryptedBytes();
        byte[] decryptedBytes = new byte[cipher.getOutputSize(cipherBytes.length)];
        final int length1 = cipher.processBytes(cipherBytes, 0, cipherBytes.length, decryptedBytes, 0);
        final int length2 = cipher.doFinal(decryptedBytes, length1);

        return Arrays.copyOf(decryptedBytes, length1 + length2);
    } catch (Exception e) {
        throw new CryptoException();
    }
}
 
Example #9
Source File: AESEncrypt.java    From nuls-v2 with MIT License 6 votes vote down vote up
/**
 * 数据通过KeyParameter和初始化向量加密
 *
 * @param plainBytes 需要加密的数据
 * @param iv         初始化向量
 * @param aesKey     秘钥
 * @return 加密后的数据
 */
public static EncryptedData encrypt(byte[] plainBytes, byte[] iv, KeyParameter aesKey) throws RuntimeException {
    HexUtil.checkNotNull(plainBytes);
    HexUtil.checkNotNull(aesKey);
    try {
        if (iv == null) {
            iv = EncryptedData.DEFAULT_IV;
            //SECURE_RANDOM.nextBytes(iv);
        }
        ParametersWithIV keyWithIv = new ParametersWithIV(aesKey, iv);
        // Encrypt using AES.
        BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));
        cipher.init(true, keyWithIv);
        byte[] encryptedBytes = new byte[cipher.getOutputSize(plainBytes.length)];
        final int length1 = cipher.processBytes(plainBytes, 0, plainBytes.length, encryptedBytes, 0);
        final int length2 = cipher.doFinal(encryptedBytes, length1);

        return new EncryptedData(iv, Arrays.copyOf(encryptedBytes, length1 + length2));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #10
Source File: BCStrongAESEncryption.java    From Hive2Hive with MIT License 6 votes vote down vote up
private static byte[] processAESCipher(boolean encrypt, byte[] data, SecretKey key, byte[] initVector)
		throws DataLengthException, IllegalStateException, InvalidCipherTextException {
	// seat up engine, block cipher mode and padding
	AESEngine aesEngine = new AESEngine();
	CBCBlockCipher cbc = new CBCBlockCipher(aesEngine);
	PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(cbc);

	// apply parameters
	CipherParameters parameters = new ParametersWithIV(new KeyParameter(key.getEncoded()), initVector);
	cipher.init(encrypt, parameters);

	// process ciphering
	byte[] output = new byte[cipher.getOutputSize(data.length)];

	int bytesProcessed1 = cipher.processBytes(data, 0, data.length, output, 0);
	int bytesProcessed2 = cipher.doFinal(output, bytesProcessed1);
	byte[] result = new byte[bytesProcessed1 + bytesProcessed2];
	System.arraycopy(output, 0, result, 0, result.length);
	return result;
}
 
Example #11
Source File: BurstCryptoImpl.java    From burstkit4j with Apache License 2.0 6 votes vote down vote up
@Override
public byte[] aesEncrypt(byte[] plaintext, byte[] signingKey, byte[] nonce) {
    if (signingKey.length != 32) {
        throw new IllegalArgumentException("Key length must be 32 bytes");
    }
    try {
        for (int i = 0; i < 32; i++) {
            signingKey[i] ^= nonce[i];
        }
        byte[] key = getSha256().digest(signingKey);
        byte[] iv = new byte[16];
        secureRandom.nextBytes(iv);
        PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()));
        CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv);
        aes.init(true, ivAndKey);
        byte[] output = new byte[aes.getOutputSize(plaintext.length)];
        int ciphertextLength = aes.processBytes(plaintext, 0, plaintext.length, output, 0);
        ciphertextLength += aes.doFinal(output, ciphertextLength);
        byte[] result = new byte[iv.length + ciphertextLength];
        System.arraycopy(iv, 0, result, 0, iv.length);
        System.arraycopy(output, 0, result, iv.length, ciphertextLength);
        return result;
    } catch (InvalidCipherTextException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
 
Example #12
Source File: BurstCryptoImpl.java    From burstkit4j with Apache License 2.0 6 votes vote down vote up
@Override
public byte[] aesDecrypt(byte[] encrypted, byte[] signingKey, byte[] nonce) {
    if (signingKey.length != 32) {
        throw new IllegalArgumentException("Key length must be 32 bytes");
    }
    try {
        if (encrypted.length < 16 || encrypted.length % 16 != 0) {
            throw new InvalidCipherTextException("invalid ciphertext");
        }
        byte[] iv = Arrays.copyOfRange(encrypted, 0, 16);
        byte[] ciphertext = Arrays.copyOfRange(encrypted, 16, encrypted.length);
        for (int i = 0; i < 32; i++) {
            signingKey[i] ^= nonce[i];
        }
        byte[] key = getSha256().digest(signingKey);
        PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()));
        CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv);
        aes.init(false, ivAndKey);
        byte[] output = new byte[aes.getOutputSize(ciphertext.length)];
        int plaintextLength = aes.processBytes(ciphertext, 0, ciphertext.length, output, 0);
        plaintextLength += aes.doFinal(output, plaintextLength);
        byte[] result = new byte[plaintextLength];
        System.arraycopy(output, 0, result, 0, result.length);
        return result;
    } catch (InvalidCipherTextException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
 
Example #13
Source File: DESEncrypter.java    From gocd with Apache License 2.0 5 votes vote down vote up
private static String encrypt(byte[] key, String plainText) throws CryptoException {
    try {
        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new DESEngine()));
        KeyParameter keyParameter = new KeyParameter(key);
        cipher.init(true, keyParameter);
        byte[] plainTextBytes = plainText.getBytes();
        byte[] cipherTextBytes = new byte[cipher.getOutputSize(plainTextBytes.length)];
        int outputLength = cipher.processBytes(plainTextBytes, 0, plainTextBytes.length, cipherTextBytes, 0);
        cipher.doFinal(cipherTextBytes, outputLength);
        return ENCODER.encodeToString(cipherTextBytes).trim();
    } catch (Exception e) {
        throw new CryptoException(e);
    }
}
 
Example #14
Source File: AESEncryptor.java    From archistar-smc with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public byte[] decrypt(byte[] data, byte[] randomKeyBytes)
        throws InvalidKeyException, InvalidAlgorithmParameterException, IOException, IllegalStateException, InvalidCipherTextException {

    PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));
    cipher.init(false, new ParametersWithIV(new KeyParameter(randomKeyBytes), randomIvBytes));
    return cipherData(cipher, data);
}
 
Example #15
Source File: GeoWaveEncryption.java    From geowave with Apache License 2.0 5 votes vote down vote up
private PaddedBufferedBlockCipher getCipher(final boolean encrypt) {
  final PaddedBufferedBlockCipher cipher =
      new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), new PKCS7Padding());
  final CipherParameters ivAndKey =
      new ParametersWithIV(new KeyParameter(getKey().getEncoded()), salt);
  cipher.init(encrypt, ivAndKey);
  return cipher;
}
 
Example #16
Source File: AESEncryptor.java    From archistar-smc with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public byte[] encrypt(byte[] data, byte[] randomKeyBytes) throws IOException, InvalidKeyException,
        InvalidAlgorithmParameterException, InvalidCipherTextException {

    PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));
    cipher.init(true, new ParametersWithIV(new KeyParameter(randomKeyBytes), randomIvBytes));
    return cipherData(cipher, data);
}
 
Example #17
Source File: Ed25519BlockCipher.java    From nem.core with MIT License 5 votes vote down vote up
private BufferedBlockCipher setupBlockCipher(final byte[] sharedKey, final byte[] ivData, final boolean forEncryption) {
	// Setup cipher parameters with key and IV.
	final KeyParameter keyParam = new KeyParameter(sharedKey);
	final CipherParameters params = new ParametersWithIV(keyParam, ivData);

	// Setup AES cipher in CBC mode with PKCS7 padding.
	final BlockCipherPadding padding = new PKCS7Padding();
	final BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), padding);
	cipher.reset();
	cipher.init(forEncryption, params);
	return cipher;
}
 
Example #18
Source File: Metodos.java    From ExamplesAndroid with Apache License 2.0 5 votes vote down vote up
public String testDecryptRijndael(String value,String key) throws DataLengthException, IllegalStateException, InvalidCipherTextException {
        BlockCipher engine = new RijndaelEngine(256);
        BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(engine), new ZeroBytePadding());

        byte[] keyBytes = key.getBytes();
        cipher.init(false, new KeyParameter(keyBytes));

        byte[] output = Base64.decode(value.getBytes());
        byte[] cipherText = new byte[cipher.getOutputSize(output.length)];

        int cipherLength = cipher.processBytes(output, 0, output.length, cipherText, 0);
        int outputLength = cipher.doFinal(cipherText, cipherLength);
        outputLength += cipherLength;

        byte[] resultBytes = cipherText;
        if (outputLength != output.length) {
            resultBytes = new byte[outputLength];
            System.arraycopy(
                    cipherText, 0,
                    resultBytes, 0,
                    outputLength
            );
        }

        String result = new String(resultBytes);
return  result;
    }
 
Example #19
Source File: DownloadDecryptFileController.java    From Spring-MVC-Blueprints with MIT License 5 votes vote down vote up
public byte[] decryptDESFile(String key, byte[] cipherText) {
BlockCipher engine = new DESEngine();
      byte[] bytes = key.getBytes();
      BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(engine));
      cipher.init(false, new KeyParameter(bytes));
      byte[] rv = new byte[cipher.getOutputSize(cipherText.length)];
      int tam = cipher.processBytes(cipherText, 0, cipherText.length, rv, 0);
      try {
          cipher.doFinal(rv, tam);
      } catch (Exception ce) {
          ce.printStackTrace();
      }
      return rv;
  }
 
Example #20
Source File: AESCipher.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/** Creates a new instance of AESCipher */
public AESCipher(boolean forEncryption, byte[] key, byte[] iv) {
    BlockCipher aes = new AESFastEngine();
    BlockCipher cbc = new CBCBlockCipher(aes);
    bp = new PaddedBufferedBlockCipher(cbc);
    KeyParameter kp = new KeyParameter(key);
    ParametersWithIV piv = new ParametersWithIV(kp, iv);
    bp.init(forEncryption, piv);
}
 
Example #21
Source File: Ed25519BlockCipher.java    From symbol-sdk-java with Apache License 2.0 5 votes vote down vote up
public static BufferedBlockCipher setupBlockCipher(
    final byte[] sharedKey, final byte[] ivData, final boolean forEncryption) {
    // Setup cipher parameters with key and IV.
    final KeyParameter keyParam = new KeyParameter(sharedKey);
    final CipherParameters params = new ParametersWithIV(keyParam, ivData);

    // Setup AES cipher in CBC mode with PKCS7 padding.
    final BlockCipherPadding padding = new PKCS7Padding();
    final BufferedBlockCipher cipher =
        new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), padding);
    cipher.reset();
    cipher.init(forEncryption, params);
    return cipher;
}
 
Example #22
Source File: AESBouncycastleUtils.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
/**
 * Method for AES CBC operation, internal call
 * 
 * @param key
 * @param icv
 * @param src
 * @param encrypting
 * @return
 * @throws GeneralSecurityException
 */
private static byte[] doAESCBC(byte[] key, byte[] icv, byte[] src, boolean encrypting) throws GeneralSecurityException {
	byte[] result = new byte[src.length];
	try {
		BufferedBlockCipher engine = new BufferedBlockCipher(new CBCBlockCipher(new AESEngine()));
		engine.init(encrypting, new ParametersWithIV(new KeyParameter(key), icv));
		int len = engine.processBytes(src, 0, src.length, result, 0);
		engine.doFinal(result, len);
	} catch (InvalidCipherTextException e) {
		throw new GeneralSecurityException(e);
	}
	return result;
}
 
Example #23
Source File: SM2PfxMaker.java    From gmhelper with Apache License 2.0 5 votes vote down vote up
/**
 * @param privKey 用户私钥
 * @param pubKey  用户公钥
 * @param cert    X509证书
 * @param passwd  口令
 * @return
 * @throws NoSuchAlgorithmException
 * @throws IOException
 * @throws PKCSException
 */
public PKCS12PfxPdu makePfx(PrivateKey privKey, PublicKey pubKey, X509Certificate cert, String passwd)
    throws NoSuchAlgorithmException, IOException, PKCSException {
    JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();

    PKCS12SafeBagBuilder eeCertBagBuilder = new JcaPKCS12SafeBagBuilder(cert);
    eeCertBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
        new DERBMPString("User Key"));
    eeCertBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
        extUtils.createSubjectKeyIdentifier(pubKey));

    char[] passwdChars = passwd.toCharArray();
    PKCS12SafeBagBuilder keyBagBuilder = new JcaPKCS12SafeBagBuilder(privKey,
        new BcPKCS12PBEOutputEncryptorBuilder(
            PKCSObjectIdentifiers.pbeWithSHAAnd3_KeyTripleDES_CBC,
            new CBCBlockCipher(new DESedeEngine())).build(passwdChars));
    keyBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
        new DERBMPString("User Key"));
    keyBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
        extUtils.createSubjectKeyIdentifier(pubKey));

    PKCS12PfxPduBuilder pfxPduBuilder = new PKCS12PfxPduBuilder();
    PKCS12SafeBag[] certs = new PKCS12SafeBag[1];
    certs[0] = eeCertBagBuilder.build();
    pfxPduBuilder.addEncryptedData(new BcPKCS12PBEOutputEncryptorBuilder(
            PKCSObjectIdentifiers.pbeWithSHAAnd40BitRC2_CBC,
            new CBCBlockCipher(new RC2Engine())).build(passwdChars),
        certs);
    pfxPduBuilder.addData(keyBagBuilder.build());
    return pfxPduBuilder.build(new BcPKCS12MacCalculatorBuilder(), passwdChars);
}
 
Example #24
Source File: DPAESCBCCipher.java    From InflatableDonkey with MIT License 4 votes vote down vote up
public DPAESCBCCipher(int blockSize) {
    this(new CBCBlockCipher(new AESEngine()), blockSize);
}
 
Example #25
Source File: StandardSecurityHandler.java    From sambox with Apache License 2.0 4 votes vote down vote up
private byte[] computeEncryptedKeyRev56(byte[] password, boolean isOwnerPassword, byte[] o,
        byte[] u, byte[] oe, byte[] ue, int encRevision) throws IOException
{
    byte[] hash, fileKeyEnc;

    if (isOwnerPassword)
    {
        byte[] oKeySalt = new byte[8];
        System.arraycopy(o, 40, oKeySalt, 0, 8);

        if (encRevision == 5)
        {
            hash = computeSHA256(password, oKeySalt, u);
        }
        else
        {
            hash = computeHash2A(password, oKeySalt, u);
        }

        fileKeyEnc = oe;
    }
    else
    {
        byte[] uKeySalt = new byte[8];
        System.arraycopy(u, 40, uKeySalt, 0, 8);

        if (encRevision == 5)
        {
            hash = computeSHA256(password, uKeySalt, null);
        }
        else
        {
            hash = computeHash2A(password, uKeySalt, null);
        }

        fileKeyEnc = ue;
    }
    try
    {
        BufferedBlockCipher cipher = new BufferedBlockCipher(
                new CBCBlockCipher(new AESFastEngine()));
        cipher.init(false, new KeyParameter(hash));
        byte[] buf = new byte[cipher.getOutputSize(fileKeyEnc.length)];
        int len = cipher.processBytes(fileKeyEnc, 0, fileKeyEnc.length, buf, 0);
        len += cipher.doFinal(buf, len);
        return copyOf(buf, len);
    }
    catch (DataLengthException | IllegalStateException | InvalidCipherTextException e)
    {
        throw new IOException(e);
    }
}
 
Example #26
Source File: AESEngineNoPadding.java    From sambox with Apache License 2.0 4 votes vote down vote up
/**
 * @return and instance of EncryptionAlgorithmEngine AES/CBC/NoPadding and no initialization vector
 */
static AESEngineNoPadding cbc()
{
    return new AESEngineNoPadding(
            new BufferedBlockCipher(new CBCBlockCipher(new AESFastEngine())));
}
 
Example #27
Source File: ConcatenatingAESEngine.java    From sambox with Apache License 2.0 4 votes vote down vote up
ConcatenatingAESEngine()
{
    super(new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine())));
    random = new SecureRandom();
}
 
Example #28
Source File: FileDecrypter.java    From LiquidDonkey with MIT License 4 votes vote down vote up
/**
 * Returns a new instance.
 *
 * @return a new instance, not null
 */
public static FileDecrypter create() {
    return FileDecrypter.from(
            new BufferedBlockCipher(new CBCBlockCipher(new AESEngine())),
            new SHA1Digest());
}
 
Example #29
Source File: CrmfKeyWrapper.java    From xipki with Apache License 2.0 4 votes vote down vote up
/**
 * Encrypt the key with the following output.
 * <pre>
 * ECIES-Ciphertext-Value ::= SEQUENCE {
 *     ephemeralPublicKey ECPoint,
 *     symmetricCiphertext OCTET STRING,
 *     macTag OCTET STRING
 * }
 *
 * ECPoint ::= OCTET STRING
 * </pre>
 */
@Override
public byte[] generateWrappedKey(byte[] keyToWrap) throws OperatorException {
  try {
    BlockCipher cbcCipher = new CBCBlockCipher(new AESEngine());
    IESCipher cipher = new IESCipher(
        new IESEngine(new ECDHBasicAgreement(),
            new KDF2BytesGenerator(new SHA1Digest()),
            new HMac(new SHA1Digest()),
            new PaddedBufferedBlockCipher(cbcCipher)), 16);

    // According to the §3.8 in SEC 1, Version 2.0:
    // "Furthermore here the 16 octet or 128 bit IV for AES in CBC mode should always take
    //  the value 0000000000000000_{16}"
    byte[] iv = new byte[16];
    IESParameterSpec spec = new IESParameterSpec(null, null, aesKeySize, aesKeySize, iv);
    cipher.engineInit(Cipher.ENCRYPT_MODE, publicKey, spec, new SecureRandom());
    byte[] bcResult = cipher.engineDoFinal(keyToWrap, 0, keyToWrap.length);
    // convert the result to ASN.1 format
    ASN1Encodable[] array = new ASN1Encodable[3];
    // ephemeralPublicKey ECPoint
    byte[] ephemeralPublicKey = new byte[ephemeralPublicKeyLen];

    System.arraycopy(bcResult, 0, ephemeralPublicKey, 0, ephemeralPublicKeyLen);
    array[0] = new DEROctetString(ephemeralPublicKey);

    // symmetricCiphertext OCTET STRING
    int symmetricCiphertextLen = bcResult.length - ephemeralPublicKeyLen - macLen;
    byte[] symmetricCiphertext = new byte[symmetricCiphertextLen];
    System.arraycopy(bcResult, ephemeralPublicKeyLen,
        symmetricCiphertext, 0, symmetricCiphertextLen);
    array[1] = new DEROctetString(symmetricCiphertext);

    // macTag OCTET STRING
    byte[] macTag = new byte[macLen];
    System.arraycopy(bcResult, ephemeralPublicKeyLen + symmetricCiphertextLen,
        macTag, 0, macLen);
    array[2] = new DEROctetString(macTag);
    return new DERSequence(array).getEncoded();
  } catch (Exception ex) {
    throw new OperatorException("error while generateWrappedKey", ex);
  }
}
 
Example #30
Source File: SM2PfxMaker.java    From gmhelper with Apache License 2.0 4 votes vote down vote up
/**
 * @param privKey 用户私钥
 * @param pubKey  用户公钥
 * @param chain   X509证书数组,切记这里固定了必须是3个元素的数组,且第一个必须是叶子证书、第二个为中级CA证书、第三个为根CA证书
 * @param passwd  口令
 * @return
 * @throws NoSuchAlgorithmException
 * @throws IOException
 * @throws PKCSException
 */
public PKCS12PfxPdu makePfx(PrivateKey privKey, PublicKey pubKey, X509Certificate[] chain, String passwd)
    throws NoSuchAlgorithmException, IOException, PKCSException {
    JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();

    PKCS12SafeBagBuilder taCertBagBuilder = new JcaPKCS12SafeBagBuilder(chain[2]);
    taCertBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
        new DERBMPString("Primary Certificate"));

    PKCS12SafeBagBuilder caCertBagBuilder = new JcaPKCS12SafeBagBuilder(chain[1]);
    caCertBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
        new DERBMPString("Intermediate Certificate"));

    PKCS12SafeBagBuilder eeCertBagBuilder = new JcaPKCS12SafeBagBuilder(chain[0]);
    eeCertBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
        new DERBMPString("User Key"));
    eeCertBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
        extUtils.createSubjectKeyIdentifier(pubKey));

    char[] passwdChars = passwd.toCharArray();
    PKCS12SafeBagBuilder keyBagBuilder = new JcaPKCS12SafeBagBuilder(privKey,
        new BcPKCS12PBEOutputEncryptorBuilder(
            PKCSObjectIdentifiers.pbeWithSHAAnd3_KeyTripleDES_CBC,
            new CBCBlockCipher(new DESedeEngine())).build(passwdChars));
    keyBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
        new DERBMPString("User Key"));
    keyBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
        extUtils.createSubjectKeyIdentifier(pubKey));

    PKCS12PfxPduBuilder pfxPduBuilder = new PKCS12PfxPduBuilder();
    PKCS12SafeBag[] certs = new PKCS12SafeBag[3];
    certs[0] = eeCertBagBuilder.build();
    certs[1] = caCertBagBuilder.build();
    certs[2] = taCertBagBuilder.build();
    pfxPduBuilder.addEncryptedData(new BcPKCS12PBEOutputEncryptorBuilder(
            PKCSObjectIdentifiers.pbeWithSHAAnd40BitRC2_CBC,
            new CBCBlockCipher(new RC2Engine())).build(passwdChars),
        certs);
    pfxPduBuilder.addData(keyBagBuilder.build());
    return pfxPduBuilder.build(new BcPKCS12MacCalculatorBuilder(), passwdChars);
}