Java 类javax.crypto.IllegalBlockSizeException 实例源码

项目:oscm    文件:PasswordSetup.java   
private String decrypt(String text) throws GeneralSecurityException {
    SecretKeySpec skeySpec = new SecretKeySpec(
            Base64.decodeBase64(ENCRYPTION_KEY), "AES");

    byte[] result;
    try {
        byte[] decoded = Base64.decodeBase64(text.getBytes());
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        result = cipher.doFinal(decoded);
    } catch (InvalidKeyException | NoSuchAlgorithmException
            | NoSuchPaddingException | IllegalBlockSizeException
            | BadPaddingException e) {
        throw new GeneralSecurityException(
                "unable to decrypt old encryption");
    }

    return new String(result);
}
项目:privacyidea-authenticator    文件:ApplicationTest.java   
@Test
public void testEncryptionHelper() throws NoSuchPaddingException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException,
        IllegalBlockSizeException, UnsupportedEncodingException, InvalidAlgorithmParameterException, DecoderException {

    // https://golang.org/src/crypto/cipher/gcm_test.go
    String[][] testCases = new String[][]{
            new String[]{"11754cd72aec309bf52f7687212e8957", "3c819d9a9bed087615030b65", "", "250327c674aaf477aef2675748cf6971"},
            new String[]{"ca47248ac0b6f8372a97ac43508308ed", "ffd2b598feabc9019262d2be", "", "60d20404af527d248d893ae495707d1a"},
            new String[]{"7fddb57453c241d03efbed3ac44e371c", "ee283a3fc75575e33efd4887", "d5de42b461646c255c87bd2962d3b9a2", "2ccda4a5415cb91e135c2a0f78c9b2fdb36d1df9b9d5e596f83e8b7f52971cb3"},
            new String[]{"ab72c77b97cb5fe9a382d9fe81ffdbed", "54cc7dc2c37ec006bcc6d1da", "007c5e5b3e59df24a7c355584fc1518d", "0e1bde206a07a9c2c1b65300f8c649972b4401346697138c7a4891ee59867d0c"},
            new String[]{"feffe9928665731c6d6a8f9467308308", "cafebabefacedbaddecaf888", "d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b391aafd255",
                    "42831ec2217774244b7221b784d0d49ce3aa212f2c02a4e035c17e2329aca12e21d514b25466931c7d8f6a5aac84aa051ba30b396a0aac973d58e091473f59854d5c2af327cd64a62cf35abd2ba6fab4"},
    };
    for (String[] testCase : testCases) {

        SecretKeySpec k = new SecretKeySpec(new Hex().decode(testCase[0].getBytes()), "AES");
        IvParameterSpec iv = new IvParameterSpec(new Hex().decode(testCase[1].getBytes()));

        byte[] cipherTExt = EncryptionHelper.encrypt(k, iv, new Hex().decode(testCase[2].getBytes()));
        String cipher = new String(new Hex().encode(cipherTExt));

        assertEquals(cipher, testCase[3]);
        assertEquals(testCase[2], new String(new Hex().encode(EncryptionHelper.decrypt(k, iv, cipherTExt))));
    }
}
项目:CustomWorldGen    文件:CryptManager.java   
/**
 * Encrypt or decrypt byte[] data using the specified key
 */
private static byte[] cipherOperation(int opMode, Key key, byte[] data)
{
    try
    {
        /**
         * Creates the Cipher Instance.
         */
        return createTheCipherInstance(opMode, key.getAlgorithm(), key).doFinal(data);
    }
    catch (IllegalBlockSizeException illegalblocksizeexception)
    {
        illegalblocksizeexception.printStackTrace();
    }
    catch (BadPaddingException badpaddingexception)
    {
        badpaddingexception.printStackTrace();
    }

    LOGGER.error("Cipher data failed!");
    return null;
}
项目:phoenix.webui.framework    文件:Encryptor.java   
/**
 * decrypt string
 * @see #encryptStr(String)
 * @param encryptStr 1
 * @return 1
 * @throws InvalidKeyException 1
 * @throws IllegalBlockSizeException 1
 * @throws BadPaddingException 1
 * @throws NullPointerException if encryptStr is null
 */
public String decryptStr(String encryptStr) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException
{
    if(encryptStr == null)
    {
        throw new NullPointerException();
    }

    encryptStr = encryptStr.toUpperCase();

    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    int len = encryptStr.length();
    for(int i = 0; i < len; i += 2)
    {
        int b = ((charToByte(encryptStr.charAt(i)) << 4) & 0xff) | charToByte(encryptStr.charAt(i + 1));
        byteOut.write(b);
    }

    return decryptStr(byteOut.toByteArray());
}
项目:openjdk-jdk10    文件:CipherWithWrappingSpi.java   
/**
 * Wrap a key.
 *
 * @param key the key to be wrapped.
 *
 * @return the wrapped key.
 *
 * @exception IllegalBlockSizeException if this cipher 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.
 *
 * @exception InvalidKeyException if it is impossible or unsafe to
 * wrap the key with this cipher (e.g., a hardware protected key is
 * being passed to a software only cipher).
 */
protected final byte[] engineWrap(Key key)
    throws IllegalBlockSizeException, InvalidKeyException
{
    byte[] result = null;

    try {
        byte[] encodedKey = key.getEncoded();
        if ((encodedKey == null) || (encodedKey.length == 0)) {
            throw new InvalidKeyException("Cannot get an encoding of " +
                                          "the key to be wrapped");
        }

        result = engineDoFinal(encodedKey, 0, encodedKey.length);
    } catch (BadPaddingException e) {
        // Should never happen
    }

    return result;
}
项目:oscm-app    文件:PasswordSetup.java   
private String decrypt(String text) throws GeneralSecurityException {
    SecretKeySpec skeySpec = new SecretKeySpec(
            Base64.decodeBase64(ENCRYPTION_KEY), "AES");

    byte[] result;
    try {
        byte[] decoded = Base64.decodeBase64(text.getBytes());
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        result = cipher.doFinal(decoded);
    } catch (InvalidKeyException | NoSuchAlgorithmException
            | NoSuchPaddingException | IllegalBlockSizeException
            | BadPaddingException e) {
        throw new GeneralSecurityException(
                "unable to decrypt old encryption");
    }

    return new String(result);
}
项目:BaseClient    文件:CryptManager.java   
/**
 * Encrypt or decrypt byte[] data using the specified key
 */
private static byte[] cipherOperation(int opMode, Key key, byte[] data)
{
    try
    {
        return createTheCipherInstance(opMode, key.getAlgorithm(), key).doFinal(data);
    }
    catch (IllegalBlockSizeException illegalblocksizeexception)
    {
        illegalblocksizeexception.printStackTrace();
    }
    catch (BadPaddingException badpaddingexception)
    {
        badpaddingexception.printStackTrace();
    }

    LOGGER.error("Cipher data failed!");
    return null;
}
项目:DecompiledMinecraft    文件:CryptManager.java   
/**
 * Encrypt or decrypt byte[] data using the specified key
 */
private static byte[] cipherOperation(int opMode, Key key, byte[] data)
{
    try
    {
        return createTheCipherInstance(opMode, key.getAlgorithm(), key).doFinal(data);
    }
    catch (IllegalBlockSizeException illegalblocksizeexception)
    {
        illegalblocksizeexception.printStackTrace();
    }
    catch (BadPaddingException badpaddingexception)
    {
        badpaddingexception.printStackTrace();
    }

    LOGGER.error("Cipher data failed!");
    return null;
}
项目:CrashCoin    文件:Main.java   
public static void main(final String[] argv) throws IOException, InvalidKeySpecException, NoSuchPaddingException, 
        InvalidKeyException, InvalidParameterSpecException, IllegalBlockSizeException, BadPaddingException,
        InvalidAlgorithmParameterException, ClassNotFoundException, GeneralSecurityException {

    if(argv.length >= 2) {
        ip = argv[0];
        port = Integer.parseInt(argv[1]);
    } else {
        Logger.getLogger(Main.class.getName()).log(Level.INFO, "Default ip and port were applied.");
        ip = Parameters.RELAY_IP;
        port = Parameters.RELAY_PORT_WALLET_LISTENER;
    }

    // Init connection with relay
    try {
        RelayConnection.getInstance();
    } catch(IOException ex) {
        Logger.getLogger(Main.class.getName()).severe(ex.getMessage());
        return;
    }

    new ClientApplication();

}
项目:PeSanKita-lib    文件:AttachmentCipherOutputStream.java   
@Override
public void flush() throws IOException {
  try {
    byte[] ciphertext = cipher.doFinal();
    byte[] auth       = mac.doFinal(ciphertext);

    messageDigest.update(ciphertext);
    this.digest = messageDigest.digest(auth);

    outputStream.write(ciphertext);
    outputStream.write(auth);

    ciphertextLength += ciphertext.length;
    ciphertextLength += auth.length;

    outputStream.flush();
  } catch (IllegalBlockSizeException | BadPaddingException e) {
    throw new AssertionError(e);
  }
}
项目:DMS    文件:AES256.java   
public static String encrypt(String str) {
    if (str == null) return null;
    Cipher cipher;
    try {
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec,
                new IvParameterSpec(ips.getBytes("UTF-8")));

        byte[] encrypted = cipher.doFinal(str.getBytes("UTF-8"));
        String Str = new String(Base64.encodeBase64(encrypted));
        return Str;
    } catch (NoSuchAlgorithmException | NoSuchPaddingException
            | InvalidKeyException | InvalidAlgorithmParameterException
            | IllegalBlockSizeException | BadPaddingException
            | UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return null;
}
项目:CryptoKnight    文件:Main.java   
public static void main(String[] args) throws InvalidKeyException, DataLengthException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException, IllegalStateException, InvalidCipherTextException
    {

        try 
        {
            UIManager.setLookAndFeel("com.pagosoft.plaf.PgsLookAndFeel");
        }

        catch (Exception e)
        {
            ;
        }
        GUI MainGUI = new GUI();
        MainGUI.ConstructGUI();

//      String CT = TextEncrypt.CBCDecrypt("8mjf2sqScPChi5lJQut6U5phB6IW8ze90WdqDm+ulLU1NWI2ODZlYzVmMjYxYTA5", "secret", 256, 0, "Q");
//      
//      System.out.println(CT);

    }
项目:CryptoKnight    文件:FileEncrypt.java   
public static String CBCEncrypt(int alg, int KeySize, String inFile, String pwd, String mode) throws NoSuchAlgorithmException, InvalidKeySpecException, DataLengthException, IllegalStateException, InvalidCipherTextException, IOException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException
{
    String res = "";

    byte[] plain = loadFile(inFile);

    Encryptor enc = new Encryptor();
    enc.setParameters(KeySize, alg);
    enc.setEncParameters(alg, pwd, KeySize, mode);
    byte[] bytesRes = enc.CBCEncrypt(plain, alg);

    save2File(inFile + ".enc", bytesRes);

    res = "Done! file contents encrypted and saved to a corresponding enc file!"; 
    return res;
}
项目:spring-data-mongodb-encrypt    文件:CryptVault.java   
public byte[] decrypt(byte[] data) {
    int version = fromSignedByte(data[0]);
    CryptVersion cryptVersion = cryptVersion(version);

    try {
        byte[] random = new byte[cryptVersion.saltLength];
        System.arraycopy(data, 1, random, 0, cryptVersion.saltLength);
        IvParameterSpec iv_spec = new IvParameterSpec(random);

        Cipher cipher = cipher(cryptVersions[version].cipher);
        cipher.init(Cipher.DECRYPT_MODE, cryptVersions[version].key, iv_spec);
        return cipher.doFinal(data, cryptVersion.saltLength + 1, data.length - cryptVersion.saltLength - 1);
    } catch (InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) {
        throw new RuntimeException("JCE exception caught while decrypting with version " + version, e);
    }
}
项目:Cybernet-VPN    文件:VpnProfile.java   
public String getSignedData(String b64data) {
    PrivateKey privkey = getKeystoreKey();
    byte[] data = Base64.decode(b64data, Base64.DEFAULT);
    // The Jelly Bean *evil* Hack
    // 4.2 implements the RSA/ECB/PKCS1PADDING in the OpenSSLprovider
    if (Build.VERSION.SDK_INT == Build.VERSION_CODES.JELLY_BEAN) {
        return processSignJellyBeans(privkey, data);
    }
    try {
        /* ECB is perfectly fine in this special case, since we are using it for
           the public/private part in the TLS exchange
         */
        @SuppressLint("GetInstance") Cipher rsaSigner = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
        rsaSigner.init(Cipher.ENCRYPT_MODE, privkey);
        byte[] signed_bytes = rsaSigner.doFinal(data);
        return Base64.encodeToString(signed_bytes, Base64.NO_WRAP);
    } catch (NoSuchAlgorithmException | InvalidKeyException | IllegalBlockSizeException
            | BadPaddingException | NoSuchPaddingException e) {
        VpnStatus.logError(R.string.error_rsa_sign, e.getClass().toString(), e.getLocalizedMessage());
        return null;
    }
}
项目:ipack    文件:JCEStreamCipher.java   
protected byte[] engineDoFinal(
    byte[]  input,
    int     inputOffset,
    int     inputLen)
    throws BadPaddingException, IllegalBlockSizeException
{
    if (inputLen != 0)
    {
        byte[] out = engineUpdate(input, inputOffset, inputLen);

        cipher.reset();

        return out;
    }

    cipher.reset();

    return new byte[0];
}
项目:ipack    文件:JCEStreamCipher.java   
protected byte[] engineWrap(
    Key     key)
throws IllegalBlockSizeException, InvalidKeyException
{
    byte[] encoded = key.getEncoded();
    if (encoded == null)
    {
        throw new InvalidKeyException("Cannot wrap key, null encoding.");
    }

    try
    {
        return engineDoFinal(encoded, 0, encoded.length);
    }
    catch (BadPaddingException e)
    {
        throw new IllegalBlockSizeException(e.getMessage());
    }
}
项目:ipack    文件:BrokenJCEBlockCipher.java   
protected byte[] engineWrap(
    Key     key) 
throws IllegalBlockSizeException, java.security.InvalidKeyException
{
    byte[] encoded = key.getEncoded();
    if (encoded == null)
    {
        throw new InvalidKeyException("Cannot wrap key, null encoding.");
    }

    try
    {
        return engineDoFinal(encoded, 0, encoded.length);
    }
    catch (BadPaddingException e)
    {
        throw new IllegalBlockSizeException(e.getMessage());
    }
}
项目:timesheet-upload    文件:EncryptDecryptUtils.java   
/**
 * Returns an encrypted value from a given String value, encrypt/encode it
 * into an URL safe String. This method uses AES algorithm for encryption
 * and Apache Base64 class to encode it into URL safe String from byte
 * array.
 *
 * @param key        --- This key is a 16byte String parameter. In ECAS it is
 *                   created using Apache RandomUtils method and is stored in the session. So
 *                   the key will be different for each session.
 * @param initVector --- This initVector is a 16byte String parameter. In
 *                   ECAS it is a constant that is maintained in each controller.
 * @param value      --- This is the input value that will be encrypted.
 * @return
 * @throws Exception
 */
public String encrypt(String key, String initVector, String value) throws Exception {
    log.debug("Inside the encrypt method of EncryptDecryptService");
    try {
        IvParameterSpec iv = new IvParameterSpec(initVector.getBytes(ENCODING));
        SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(ENCODING), ALGORITHM_AES);

        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);

        byte[] encrypted = cipher.doFinal(value.getBytes());
        log.info("Encrypted string: " + Base64.encodeBase64URLSafeString(encrypted));

        return Base64.encodeBase64URLSafeString(encrypted);
    } catch (UnsupportedEncodingException | InvalidAlgorithmParameterException | InvalidKeyException | NoSuchAlgorithmException | BadPaddingException | IllegalBlockSizeException | NoSuchPaddingException ex) {
        log.error("Error while encryption: " + ex);
        throw ex;
    }

}
项目:ipack    文件:AsymmetricBlockCipher.java   
/**
 * Finish a multiple-part encryption or decryption operation (depending on
 * how this cipher was initialized).
 *
 * @param input  the input buffer
 * @param inOff  the offset where the input starts
 * @param inLen  the input length
 * @param output the buffer for the result
 * @param outOff the offset where the result is stored
 * @return the output length
 * @throws ShortBufferException if the output buffer is too small to hold the result.
 * @throws IllegalBlockSizeException if the plaintext or ciphertext size is too large.
 * @throws BadPaddingException if the ciphertext is invalid.
 */
public final int doFinal(byte[] input, int inOff, int inLen, byte[] output,
                         int outOff)
    throws ShortBufferException, IllegalBlockSizeException,
    BadPaddingException
{

    if (output.length < getOutputSize(inLen))
    {
        throw new ShortBufferException("Output buffer too short.");
    }

    byte[] out = doFinal(input, inOff, inLen);
    System.arraycopy(out, 0, output, outOff, out.length);
    return out.length;
}
项目:jdk8u-jdk    文件:CipherWithWrappingSpi.java   
/**
 * Wrap a key.
 *
 * @param key the key to be wrapped.
 *
 * @return the wrapped key.
 *
 * @exception IllegalBlockSizeException if this cipher 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.
 *
 * @exception InvalidKeyException if it is impossible or unsafe to
 * wrap the key with this cipher (e.g., a hardware protected key is
 * being passed to a software only cipher).
 */
protected final byte[] engineWrap(Key key)
    throws IllegalBlockSizeException, InvalidKeyException
{
    byte[] result = null;

    try {
        byte[] encodedKey = key.getEncoded();
        if ((encodedKey == null) || (encodedKey.length == 0)) {
            throw new InvalidKeyException("Cannot get an encoding of " +
                                          "the key to be wrapped");
        }

        result = engineDoFinal(encodedKey, 0, encodedKey.length);
    } catch (BadPaddingException e) {
        // Should never happen
    }

    return result;
}
项目:ipack    文件:BaseWrapCipher.java   
protected byte[] engineWrap(
    Key     key)
throws IllegalBlockSizeException, InvalidKeyException
{
    byte[] encoded = key.getEncoded();
    if (encoded == null)
    {
        throw new InvalidKeyException("Cannot wrap key, null encoding.");
    }

    try
    {
        if (wrapEngine == null)
        {
            return engineDoFinal(encoded, 0, encoded.length);
        }
        else
        {
            return wrapEngine.wrap(encoded, 0, encoded.length);
        }
    }
    catch (BadPaddingException e)
    {
        throw new IllegalBlockSizeException(e.getMessage());
    }
}
项目:ipack    文件:BaseCipherSpi.java   
protected byte[] engineWrap(
    Key     key)
throws IllegalBlockSizeException, InvalidKeyException
{
    byte[] encoded = key.getEncoded();
    if (encoded == null)
    {
        throw new InvalidKeyException("Cannot wrap key, null encoding.");
    }

    try
    {
        if (wrapEngine == null)
        {
            return engineDoFinal(encoded, 0, encoded.length);
        }
        else
        {
            return wrapEngine.wrap(encoded, 0, encoded.length);
        }
    }
    catch (BadPaddingException e)
    {
        throw new IllegalBlockSizeException(e.getMessage());
    }
}
项目:openjdk-jdk10    文件:CipherNCFuncTest.java   
public static void main(String[] args) throws ShortBufferException,
        IllegalBlockSizeException, BadPaddingException {
    byte[] plainText = new byte[801];
    // Initialization
    RandomFactory.getRandom().nextBytes(plainText);
    Cipher ci = new NullCipher();
    // Encryption
    byte[] cipherText = new byte[ci.getOutputSize(plainText.length)];
    int offset = ci.update(plainText, 0, plainText.length, cipherText, 0);
    ci.doFinal(cipherText, offset);
    // Decryption
    byte[] recoveredText = new byte[ci.getOutputSize(cipherText.length)];
    int len = ci.doFinal(cipherText, 0, cipherText.length, recoveredText);
    // Comparison
    if (len != plainText.length ||
            !TestUtilities.equalsBlock(plainText, cipherText, len) ||
            !TestUtilities.equalsBlock(plainText, recoveredText, len)) {
        throw new RuntimeException(
            "Test failed because plainText not equal to cipherText and revoveredText");
    }
}
项目:Mevius-IO    文件:MeviusTransferPacket.java   
public static MeviusTransferPacket getInstance(PublicKey publickey, MeviusPacket packet)
        throws MeviusCipherException {
    try {
        DESedeKeySpec desKeySpec = new DESedeKeySpec(((String) MeviusCipherKey.randomDESKey().getKey()).getBytes());
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
        Key key = keyFactory.generateSecret(desKeySpec);
        Cipher c = Cipher.getInstance("RSA/ECB/PKCS1PADDING", "SunJCE");
        c.init(Cipher.ENCRYPT_MODE, publickey);
        byte[] bkey = convertObj(key, c);
        c = Cipher.getInstance("DESede/ECB/PKCS5Padding");
        c.init(Cipher.ENCRYPT_MODE, key);
        byte[] bobj = convertObj(packet, c);
        return new MeviusTransferPacket(bkey, bobj);
    } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException
            | IOException | InvalidKeySpecException | IllegalBlockSizeException | BadPaddingException e) {
        e.printStackTrace();
        throw new MeviusCipherException(e.getLocalizedMessage());
    }
}
项目:Backmemed    文件:CryptManager.java   
/**
 * Encrypt or decrypt byte[] data using the specified key
 */
private static byte[] cipherOperation(int opMode, Key key, byte[] data)
{
    try
    {
        return createTheCipherInstance(opMode, key.getAlgorithm(), key).doFinal(data);
    }
    catch (IllegalBlockSizeException illegalblocksizeexception)
    {
        illegalblocksizeexception.printStackTrace();
    }
    catch (BadPaddingException badpaddingexception)
    {
        badpaddingexception.printStackTrace();
    }

    LOGGER.error("Cipher data failed!");
    return null;
}
项目:CrashCoin    文件:Wallet.java   
private PrivateKey readWalletFile(final char[] userPassword) throws FileNotFoundException,
        IOException, ClassNotFoundException, InvalidKeySpecException,
        InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException {

    final WalletInformation walletInformation;
    try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
        walletInformation = (WalletInformation) ois.readObject();
    } catch(IOException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, "Error with file {0}", ex.getMessage());
        return null;
    }

    final KeyPair keyPair = Cryptography.keyPairFromWalletInformation(userPassword, walletInformation);
    if (keyPair == null) {
        System.out.println("The password you entered is incorrect");
        return null;
    }
    this.publicKey = keyPair.getPublic();
    return keyPair.getPrivate();
}
项目:PeSanKita-android    文件:EncryptingPartOutputStream.java   
@Override
public void close() throws IOException {
  try {
    if (!closed) {
      byte[] encryptedRemainder = cipher.doFinal();
      mac.update(encryptedRemainder);

      byte[] macBytes = mac.doFinal();

      super.write(encryptedRemainder, 0, encryptedRemainder.length);
      super.write(macBytes, 0, macBytes.length);

      closed = true;
    }

    super.close();
  } catch (BadPaddingException bpe) {
    throw new AssertionError(bpe);
  } catch (IllegalBlockSizeException e) {
    throw new AssertionError(e);
  }
}
项目:Daejeon-People    文件:AES.java   
public static String encrypt(String str) {
    if (str == null) return null;
    Cipher cipher;
    try {
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec,
                new IvParameterSpec(ips.getBytes("UTF-8")));

        byte[] encrypted = cipher.doFinal(str.getBytes("UTF-8"));
        String Str = new String(Base64.encodeBase64(encrypted));
        return Str;
    } catch (NoSuchAlgorithmException | NoSuchPaddingException
            | InvalidKeyException | InvalidAlgorithmParameterException
            | IllegalBlockSizeException | BadPaddingException
            | UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return null;
}
项目:dracoon-dropzone    文件:CryptoUtil.java   
private byte[] decrypt(byte[] cipherText, byte[] key, byte[] initialVector)
        throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
        InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
    Cipher cipher = Cipher.getInstance(cipherTransformation);
    SecretKeySpec secretKeySpecy = new SecretKeySpec(key, aesEncryptionAlgorithm);
    IvParameterSpec ivParameterSpec = new IvParameterSpec(initialVector);
    cipher.init(Cipher.DECRYPT_MODE, secretKeySpecy, ivParameterSpec);
    cipherText = cipher.doFinal(cipherText);
    return cipherText;
}
项目:jdk8u-jdk    文件:CipherNCFuncTest.java   
public static void main(String[] args) throws ShortBufferException,
        IllegalBlockSizeException, BadPaddingException {
    byte[] plainText = new byte[801];
    // Initialization
    RandomFactory.getRandom().nextBytes(plainText);
    Cipher ci = new NullCipher();
    // Encryption
    byte[] cipherText = new byte[ci.getOutputSize(plainText.length)];
    int offset = ci.update(plainText, 0, plainText.length, cipherText, 0);
    ci.doFinal(cipherText, offset);
    // Decryption
    byte[] recoveredText = new byte[ci.getOutputSize(cipherText.length)];
    int len = ci.doFinal(cipherText, 0, cipherText.length, recoveredText);
    // Comparison
    if (len != plainText.length ||
            !TestUtilities.equalsBlock(plainText, cipherText, len) ||
            !TestUtilities.equalsBlock(plainText, recoveredText, len)) {
        throw new RuntimeException(
            "Test failed because plainText not equal to cipherText and revoveredText");
    }
}
项目:dracoon-dropzone    文件:CryptoUtil.java   
public String encrypt(String plainText, String key) {
    String encodedString = "";

    try {
        byte[] plainTextbytes = plainText.getBytes(characterEncoding);
        byte[] keyBytes = getKeyBytes(KEY_PREFIX + "" + key);
        encodedString = Base64.getEncoder().encodeToString(encrypt(plainTextbytes, keyBytes, keyBytes));
    } catch (UnsupportedEncodingException | InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException
            | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return encodedString;

}
项目:openjdk-jdk10    文件:GCTR.java   
int doFinal(byte[] in, int inOfs, int inLen, byte[] out,
                      int outOfs) throws IllegalBlockSizeException {
    try {
        if (inLen < 0) {
            throw new IllegalBlockSizeException("Negative input size!");
        } else if (inLen > 0) {
            int lastBlockSize = inLen % AES_BLOCK_SIZE;
            int completeBlkLen = inLen - lastBlockSize;
            // process the complete blocks first
            update(in, inOfs, completeBlkLen, out, outOfs);
            if (lastBlockSize != 0) {
                // do the last partial block
                byte[] encryptedCntr = new byte[AES_BLOCK_SIZE];
                embeddedCipher.encryptBlock(counter, 0, encryptedCntr, 0);
                for (int n = 0; n < lastBlockSize; n++) {
                    out[outOfs + completeBlkLen + n] =
                        (byte) ((in[inOfs + completeBlkLen + n] ^
                                 encryptedCntr[n]));
                }
            }
        }
    } finally {
        reset();
    }
    return inLen;
}
项目:paillier    文件:PaillierCipher.java   
/**
 * Calls the second overloaded version of the same method.
 */
protected final byte[] engineDoFinal(byte[] input, int inputOffset, int inputLen)
        throws IllegalBlockSizeException, BadPaddingException {
    int length = 0;
    byte[] out = new byte[engineGetOutputSize(inputLen)];
    try {
        length = engineDoFinal(input, inputOffset, inputLen, out, 0);
    } catch (ShortBufferException sbe) {

    }
    if (length < out.length) {
        byte[] smaller = new byte[length];
        System.arraycopy(out, 0, smaller, 0, length);
    }
    return out;
}
项目:jdk8u-jdk    文件:CipherInputStreamExceptions.java   
static void cbc_readAllIllegalBlockSize() throws Exception {
    byte[] read = new byte[200];

    System.out.println("Running cbc_readAllIllegalBlockSize test");

    // Encrypt 96 byte with AES/CBC/PKCS5Padding
    byte[] ct = encryptedText("CBC", 96);
    // Create a stream with only 95 bytes of encrypted data
    CipherInputStream in = getStream("CBC", ct, 95);

    try {
        int s, size = 0;
        while ((s = in.read(read)) != -1) {
            size += s;
        }
        throw new RuntimeException("Fail: No IllegalBlockSizeException. " +
                "CipherInputStream.read() returned " + size);

    } catch (IOException e) {
        Throwable ec = e.getCause();
        if (ec instanceof IllegalBlockSizeException) {
            System.out.println("  Pass.");
        } else {
            System.out.println("  Fail: " + ec.getMessage());
            throw new RuntimeException(ec);
        }
    }
}
项目:paillier    文件:PaillierHomomorphicCipher.java   
/**
 * Calls the second overloaded version of the same method,
 * to perform the required operation based on the state of the cipher.
 * 
 * @return returns the result from encryption or decryption
 */
protected final byte[] engineDoFinal(byte[] input, int inputOffset, int inputLen)
        throws IllegalBlockSizeException, BadPaddingException {

    byte[] out = new byte[engineGetOutputSize(inputLen)];
    try {
         engineDoFinal(input, inputOffset, inputLen, out, 0);
    } catch (ShortBufferException sbe) {
    }

    return out;
}
项目:openjdk-jdk10    文件:NativeRSACipher.java   
private int doFinal(byte[] out, int outOfs, int outLen)
        throws ShortBufferException, IllegalBlockSizeException,
        BadPaddingException {
    if (bufOfs > buffer.length) {
        throw new IllegalBlockSizeException(
            "Data must not be longer than " +
            (buffer.length - (encrypt ? padLen : 0)) + " bytes");
    }
    if (outLen < outputSize) {
        throw new ShortBufferException();
    }
    try {
        long keyValue = key.value();
        int k = nativeAtomic(mech.value(), encrypt, keyValue,
                             key.length(), buffer, bufOfs,
                             out, outOfs, outLen);
        if (k < 0) {
            if ( k == -16 || k == -64) {
                // -16: CRYPTO_ENCRYPTED_DATA_INVALID
                // -64: CKR_ENCRYPTED_DATA_INVALID, see bug 17459266
                UcryptoException ue = new UcryptoException(16);
                BadPaddingException bpe =
                    new BadPaddingException("Invalid encryption data");
                bpe.initCause(ue);
                throw bpe;
            }
            throw new UcryptoException(-k);
        }

        return k;
    } finally {
        bufOfs = 0;
    }
}
项目:wolfcrypt-jni    文件:WolfCryptCipher.java   
@Override
protected byte[] engineDoFinal(byte[] input, int inputOffset,
        int inputLen)
    throws IllegalBlockSizeException, BadPaddingException {

    if (debug.DEBUG)
        log("final (offset: " + inputOffset + ", len: " +
            inputLen + ")");

    return wolfCryptFinal(input, inputOffset, inputLen);
}
项目:SecureUtils    文件:AES256PKCS5Padding.java   
public static String decryptAES256PKCS5Padding(String key, String src)
        throws NoSuchPaddingException, NoSuchAlgorithmException,
        IOException, InvalidAlgorithmParameterException,
        InvalidKeyException, BadPaddingException,
        IllegalBlockSizeException {
    Cipher cipher = Cipher.getInstance(ALGORITHM_ENCODING);
    cipher.init(Cipher.DECRYPT_MODE, generateKeyAES256(key),
            new IvParameterSpec(new byte[cipher.getBlockSize()]));
    return new String(cipher.doFinal(Base64.decode(src)));
}
项目:Lucid2.0    文件:MapleAESOFB.java   
/**
 * Encrypts <code>data</code> and generates a new IV.
 *
 * @param data The bytes to encrypt.
 * @return The encrypted bytes.
 */
public byte[] crypt(byte[] data) {
    int remaining = data.length;
    int llength = 0x5B0;
    int start = 0;

    try {
        while (remaining > 0) {
            byte[] myIv = BitTools.multiplyBytes(this.iv, 4, 4);
            if (remaining < llength) {
                llength = remaining;
            }
            for (int x = start; x < (start + llength); x++) {
                if ((x - start) % myIv.length == 0) {
                    byte[] newIv = cipher.doFinal(myIv);
                    System.arraycopy(newIv, 0, myIv, 0, myIv.length);
                    // System.out
                    // .println("Iv is now " + HexTool.toString(this.iv));

                }
                data[x] ^= myIv[(x - start) % myIv.length];
            }
            start += llength;
            remaining -= llength;
            llength = 0x5B4;
        }
        updateIv();
    } catch (IllegalBlockSizeException | BadPaddingException e) {
    }
    return data;
}