javax.crypto.BadPaddingException Java Examples

The following examples show how to use javax.crypto.BadPaddingException. 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: CipherWithWrappingSpi.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #2
Source File: CipherCore.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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).
 */
byte[] wrap(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 = doFinal(encodedKey, 0, encodedKey.length);
    } catch (BadPaddingException e) {
        // Should never happen
    }
    return result;
}
 
Example #3
Source File: McElieceKobaraImaiCipherSpi.java    From ripple-lib-java with ISC License 6 votes vote down vote up
/**
 * Unpad a message.
 *
 * @param pmBytes the padded message
 * @return the message
 * @throws BadPaddingException if the padded message is invalid.
 */
private byte[] unpad(byte[] pmBytes)
    throws BadPaddingException
{
    // find first non-zero byte
    int index;
    for (index = pmBytes.length - 1; index >= 0 && pmBytes[index] == 0; index--)
    {
        ;
    }

    // check if padding byte is valid
    if (pmBytes[index] != 0x01)
    {
        throw new BadPaddingException("invalid ciphertext");
    }

    // extract and return message
    byte[] mBytes = new byte[index];
    System.arraycopy(pmBytes, 0, mBytes, 0, index);
    return mBytes;
}
 
Example #4
Source File: LocalChannelSender.java    From protect with MIT License 6 votes vote down vote up
/**
 * Broadcasts messages to all listeners who have registered with this channel
 * 
 * @param message
 */
@Override
public void broadcast(final SignedMessage message) {

	synchronized (this.registeredListeners) {
		// Serialize message to bytes
		byte[] serializedMessage = MessageSerializer.serializeSignedMessage(message);

		for (final ChannelListener listener : this.registeredListeners) {
			try {
				listener.receiveSerializedMessage(serializedMessage);
			} catch (ClassNotFoundException | BadPaddingException | IllegalBlockSizeException | IOException e) {
				e.printStackTrace();
			}
		}
	}

}
 
Example #5
Source File: RSAPadding.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Pad the data and return the padded block.
 */
public byte[] pad(byte[] data) throws BadPaddingException {
    if (data.length > maxDataSize) {
        throw new BadPaddingException("Data must be shorter than "
            + (maxDataSize + 1) + " bytes");
    }
    switch (type) {
    case PAD_NONE:
        return data;
    case PAD_BLOCKTYPE_1:
    case PAD_BLOCKTYPE_2:
        return padV15(data);
    case PAD_OAEP_MGF1:
        return padOAEP(data);
    default:
        throw new AssertionError();
    }
}
 
Example #6
Source File: DataCipher.java    From onboard with Apache License 2.0 6 votes vote down vote up
/**
 * 解密方法
 * 
 */
private static byte[] decrypt(byte[] encryptedData) throws IllegalBlockSizeException, BadPaddingException,
        InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException {
    // DES算法要求有一个可信任的随机数源
    SecureRandom sr = new SecureRandom();
    // 从原始密匙数据创建一个DESKeySpec对象
    DESKeySpec dks = new DESKeySpec(getRawKeyData());
    // 创建一个密匙工厂,然后用它把DESKeySpec对象转换成一个SecretKey对象
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
    SecretKey key = keyFactory.generateSecret(dks);
    // Cipher对象实际完成解密操作
    Cipher cipher = Cipher.getInstance("DES");
    // 用密匙初始化Cipher对象
    cipher.init(Cipher.DECRYPT_MODE, key, sr);
    // 正式执行解密操作
    byte decryptedData[] = cipher.doFinal(encryptedData);
    return decryptedData;
}
 
Example #7
Source File: KeyStore.java    From BlockchainWallet-Crypto with GNU General Public License v3.0 6 votes vote down vote up
private static byte[] performCipherOperation(
        int mode, byte[] iv, byte[] encryptKey, byte[] text) throws CipherException {

    try {
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
        Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");

        SecretKeySpec secretKeySpec = new SecretKeySpec(encryptKey, "AES");
        cipher.init(mode, secretKeySpec, ivParameterSpec);
        return cipher.doFinal(text);
    } catch (NoSuchPaddingException | NoSuchAlgorithmException
            | InvalidAlgorithmParameterException | InvalidKeyException
            | BadPaddingException | IllegalBlockSizeException e) {
        throw new CipherException("Error performing cipher operation", e);
    }
}
 
Example #8
Source File: CipherInputStream.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Closes this input stream and releases any system resources
 * associated with the stream.
 * <p>
 * The <code>close</code> method of <code>CipherInputStream</code>
 * calls the <code>close</code> method of its underlying input
 * stream.
 *
 * @exception  IOException  if an I/O error occurs.
 * @since JCE1.2
 */
public void close() throws IOException {
    if (closed) {
        return;
    }

    closed = true;
    input.close();

    // Throw away the unprocessed data and throw no crypto exceptions.
    // AEAD ciphers are fully readed before closing.  Any authentication
    // exceptions would occur while reading.
    if (!done) {
        try {
            cipher.doFinal();
        }
        catch (BadPaddingException | IllegalBlockSizeException ex) {
            // Catch exceptions as the rest of the stream is unused.
        }
    }
    ostart = 0;
    ofinish = 0;
}
 
Example #9
Source File: CipherCore.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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).
 */
byte[] wrap(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 = doFinal(encodedKey, 0, encodedKey.length);
    } catch (BadPaddingException e) {
        // Should never happen
    }
    return result;
}
 
Example #10
Source File: CryptVault.java    From spring-data-mongodb-encrypt with Apache License 2.0 6 votes vote down vote up
public byte[] encrypt(int version, byte[] data) {
    CryptVersion cryptVersion = cryptVersion(version);
    try {
        int cryptedLength = cryptVersion.encryptedLength.apply(data.length);
        byte[] result = new byte[cryptedLength + cryptVersion.saltLength + 1];
        result[0] = toSignedByte(version);

        byte[] random = urandomBytes(cryptVersion.saltLength);
        IvParameterSpec iv_spec = new IvParameterSpec(random);
        System.arraycopy(random, 0, result, 1, cryptVersion.saltLength);

        Cipher cipher = cipher(cryptVersion.cipher);
        cipher.init(Cipher.ENCRYPT_MODE, cryptVersion.key, iv_spec);
        int len = cipher.doFinal(data, 0, data.length, result, cryptVersion.saltLength + 1);

        if (len < cryptedLength) LOG.info("len was " + len + " instead of " + cryptedLength);

        return result;
    } catch (ShortBufferException | IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException | InvalidKeyException e) {
        // wrap checked exception for easy use
        throw new CryptOperationException("JCE exception caught while encrypting with version " + version, e);
    }
}
 
Example #11
Source File: LogFile.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
void writeEntry(@NonNull String entry) throws IOException {
  new SecureRandom().nextBytes(ivBuffer);

  byte[] plaintext = entry.getBytes();
  try {
    cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(secret, "AES"), new IvParameterSpec(ivBuffer));

    int    cipherLength = cipher.getOutputSize(plaintext.length);
    byte[] ciphertext   = ciphertextBuffer.get(cipherLength);
    cipherLength = cipher.doFinal(plaintext, 0, plaintext.length, ciphertext);

    outputStream.write(ivBuffer);
    outputStream.write(Conversions.intToByteArray(cipherLength));
    outputStream.write(ciphertext, 0, cipherLength);

    outputStream.flush();
  } catch (ShortBufferException | InvalidAlgorithmParameterException | InvalidKeyException | BadPaddingException | IllegalBlockSizeException e) {
    throw new AssertionError(e);
  }
}
 
Example #12
Source File: KeyStoreHelper.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@RequiresApi(Build.VERSION_CODES.M)
public static SealedData seal(@NonNull byte[] input) {
  SecretKey secretKey = getOrCreateKeyStoreEntry();

  try {
    Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
    cipher.init(Cipher.ENCRYPT_MODE, secretKey);

    byte[] iv   = cipher.getIV();
    byte[] data = cipher.doFinal(input);

    return new SealedData(iv, data);
  } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
    throw new AssertionError(e);
  }
}
 
Example #13
Source File: ExtendedKey.java    From bop-bitcoin-client with Apache License 2.0 6 votes vote down vote up
public byte[] encrypt (String passphrase, boolean production) throws ValidationException
{
	try
	{
		byte[] key = SCrypt.generate (passphrase.getBytes ("UTF-8"), BITCOIN_SEED, 16384, 8, 8, 32);
		SecretKeySpec keyspec = new SecretKeySpec (key, "AES");
		Cipher cipher = Cipher.getInstance ("AES/CBC/PKCS5Padding", "BC");
		cipher.init (Cipher.ENCRYPT_MODE, keyspec);
		byte[] iv = cipher.getIV ();
		byte[] c = cipher.doFinal (serialize (production).getBytes ());
		byte[] result = new byte[iv.length + c.length];
		System.arraycopy (iv, 0, result, 0, iv.length);
		System.arraycopy (c, 0, result, iv.length, c.length);
		return result;
	}
	catch ( UnsupportedEncodingException | NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException | InvalidKeyException
			| IllegalBlockSizeException | BadPaddingException e )
	{
		throw new ValidationException (e);
	}
}
 
Example #14
Source File: ToolElGamal.java    From protools with Apache License 2.0 6 votes vote down vote up
/**
 * 用公钥加密
 *
 * @param data
 *         待加密数据
 * @param key
 *         公钥
 *
 * @return byte[] 加密数据
 *
 * @throws Exception
 */
public static byte[] encryptByPublicKey(byte[] data, byte[] key) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
    // 加入BouncyCastleProvider支持
    Security.addProvider(new BouncyCastleProvider());

    // 公钥材料转换
    X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);

    // 实例化密钥工厂
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

    // 生成公钥
    Key publicKey = keyFactory.generatePublic(x509KeySpec);

    // 对数据加密
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());

    cipher.init(Cipher.ENCRYPT_MODE, publicKey);

    return cipher.doFinal(data);
}
 
Example #15
Source File: TestCipher.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
public void runAll() throws InvalidKeyException,
        NoSuchPaddingException, InvalidAlgorithmParameterException,
        ShortBufferException, IllegalBlockSizeException,
        BadPaddingException, NoSuchAlgorithmException,
        NoSuchProviderException {

    for (String mode : MODES) {
        for (String padding : PADDINGS) {
            if (!isMultipleKeyLengthSupported()) {
                runTest(mode, padding, minKeySize);
            } else {
                int keySize = maxKeySize;
                while (keySize >= minKeySize) {
                    out.println("With Key Strength: " + keySize);
                    runTest(mode, padding, keySize);
                    keySize -= KEYCUTTER;
                }
            }
        }
    }
}
 
Example #16
Source File: RSAPadding.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Compute MGF1 using mgfMD as the message digest.
 * Note that we combine MGF1 with the XOR operation to reduce data
 * copying.
 *
 * We generate maskLen bytes of MGF1 from the seed and XOR it into
 * out[] starting at outOfs;
 */
private void mgf1(byte[] seed, int seedOfs, int seedLen,
        byte[] out, int outOfs, int maskLen)  throws BadPaddingException {
    byte[] C = new byte[4]; // 32 bit counter
    byte[] digest = new byte[mgfMd.getDigestLength()];
    while (maskLen > 0) {
        mgfMd.update(seed, seedOfs, seedLen);
        mgfMd.update(C);
        try {
            mgfMd.digest(digest, 0, digest.length);
        } catch (DigestException e) {
            // should never happen
            throw new BadPaddingException(e.toString());
        }
        for (int i = 0; (i < digest.length) && (maskLen > 0); maskLen--) {
            out[outOfs++] ^= digest[i++];
        }
        if (maskLen > 0) {
            // increment counter
            for (int i = C.length - 1; (++C[i] == 0) && (i > 0); i--) {
                // empty
            }
        }
    }
}
 
Example #17
Source File: CcAes.java    From takes with MIT License 6 votes vote down vote up
/**
 * Decrypt the given bytes using AES.
 *
 * @param bytes Bytes to decrypt
 * @return Decrypted bytes
 * @throws IOException for all unexpected exceptions
 */
private byte[] decrypt(final byte[] bytes) throws IOException {
    if (bytes.length < CcAes.BLOCK << 1) {
        throw new DecodingException("Invalid encrypted message format");
    }
    try {
        final byte[] vector = new byte[CcAes.BLOCK];
        final byte[] message = new byte[bytes.length - vector.length];
        System.arraycopy(bytes, 0, vector, 0, vector.length);
        System.arraycopy(
            bytes,
            vector.length,
            message,
            0,
            message.length
        );
        return this.cipher(
            Cipher.DECRYPT_MODE,
            new IvParameterSpec(vector)
        ).doFinal(message);
    } catch (final BadPaddingException | IllegalBlockSizeException ex) {
        throw new DecodingException(ex);
    }
}
 
Example #18
Source File: SymmetricCryptograph.java    From cassandra-reaper with Apache License 2.0 6 votes vote down vote up
private String decryptText(String key, String encryptedText) throws InvalidKeySpecException, NoSuchAlgorithmException,
        NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException,
        InvalidAlgorithmParameterException {
  byte[] encryptedData = decode(encryptedText);
  if (encryptedData.length <= 16) {
    throw new IllegalArgumentException("Invalid format for supplied encrypted value");
  }

  byte[] initVector = subArray(encryptedData, 0, 16);
  byte[] encryptedBytes = subArray(encryptedData, initVector.length, encryptedData.length);

  IvParameterSpec ivspec = new IvParameterSpec(initVector);
  SecretKey secretKey = createSecretKey(key);

  Cipher decipher = Cipher.getInstance(cipher);
  decipher.init(Cipher.DECRYPT_MODE, secretKey, ivspec);
  byte[] decryptedBytes = decipher.doFinal(encryptedBytes);

  return new String(decryptedBytes, StandardCharsets.UTF_8);
}
 
Example #19
Source File: CipherInputStream.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Closes this input stream and releases any system resources
 * associated with the stream.
 * <p>
 * The <code>close</code> method of <code>CipherInputStream</code>
 * calls the <code>close</code> method of its underlying input
 * stream.
 *
 * @exception  IOException  if an I/O error occurs.
 * @since JCE1.2
 */
public void close() throws IOException {
    if (closed) {
        return;
    }

    closed = true;
    input.close();

    // Android-removed: Removed a now-inaccurate comment
    if (!done) {
        try {
            cipher.doFinal();
        }
        catch (BadPaddingException | IllegalBlockSizeException ex) {
            // Android-changed: Added throw if bad tag is seen.  See b/31590622.
            if (ex instanceof AEADBadTagException) {
                throw new IOException(ex);
            }
        }
    }
    ostart = 0;
    ofinish = 0;
}
 
Example #20
Source File: CipherNCFuncTest.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
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");
    }
}
 
Example #21
Source File: AesCbcHmacSha2.java    From azure-keyvault-java with MIT License 6 votes vote down vote up
@Override
public byte[] doFinal(byte[] input) throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException {

    // Add the cipher text to the running hash
    _hmac.update(input);

    // Add the associated_data_length bytes to the hash
    byte[] hash = _hmac.doFinal(_aad_length);

    // Compute the new tag
    byte[] tag = new byte[_hmac_key.length];
    System.arraycopy(hash, 0, tag, 0, _hmac_key.length);
    
    // Check the tag before performing the final decrypt
    if ( !ByteExtensions.sequenceEqualConstantTime(_tag, tag) ) {
        throw new IllegalArgumentException("Data is not authentic");
    }

    return _inner.doFinal(input);
}
 
Example #22
Source File: RSAPadding.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Pad the data and return the padded block.
 */
public byte[] pad(byte[] data) throws BadPaddingException {
    if (data.length > maxDataSize) {
        throw new BadPaddingException("Data must be shorter than "
            + (maxDataSize + 1) + " bytes but received "
            + data.length + " bytes.");
    }
    switch (type) {
    case PAD_NONE:
        return data;
    case PAD_BLOCKTYPE_1:
    case PAD_BLOCKTYPE_2:
        return padV15(data);
    case PAD_OAEP_MGF1:
        return padOAEP(data);
    default:
        throw new AssertionError();
    }
}
 
Example #23
Source File: Wallet.java    From gsc-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static byte[] performCipherOperation(
        int mode, byte[] iv, byte[] encryptKey, byte[] text) throws CipherException {

    try {
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
        Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");

        SecretKeySpec secretKeySpec = new SecretKeySpec(encryptKey, "AES");
        cipher.init(mode, secretKeySpec, ivParameterSpec);
        return cipher.doFinal(text);
    } catch (NoSuchPaddingException | NoSuchAlgorithmException
            | InvalidAlgorithmParameterException | InvalidKeyException
            | BadPaddingException | IllegalBlockSizeException e) {
        throw new CipherException("Error performing cipher operation", e);
    }
}
 
Example #24
Source File: XmppAxolotlMessage.java    From Conversations with GNU General Public License v3.0 5 votes vote down vote up
public XmppAxolotlPlaintextMessage decrypt(XmppAxolotlSession session, Integer sourceDeviceId) throws CryptoFailedException {
    XmppAxolotlPlaintextMessage plaintextMessage = null;
    byte[] key = unpackKey(session, sourceDeviceId);
    if (key != null) {
        try {
            if (key.length < 32) {
                throw new OutdatedSenderException("Key did not contain auth tag. Sender needs to update their OMEMO client");
            }
            final int authTagLength = key.length - 16;
            byte[] newCipherText = new byte[key.length - 16 + ciphertext.length];
            byte[] newKey = new byte[16];
            System.arraycopy(ciphertext, 0, newCipherText, 0, ciphertext.length);
            System.arraycopy(key, 16, newCipherText, ciphertext.length, authTagLength);
            System.arraycopy(key, 0, newKey, 0, newKey.length);
            ciphertext = newCipherText;
            key = newKey;

            final Cipher cipher = Compatibility.twentyEight() ? Cipher.getInstance(CIPHERMODE) : Cipher.getInstance(CIPHERMODE, PROVIDER);
            SecretKeySpec keySpec = new SecretKeySpec(key, KEYTYPE);
            IvParameterSpec ivSpec = new IvParameterSpec(iv);

            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);

            String plaintext = new String(cipher.doFinal(ciphertext));
            plaintextMessage = new XmppAxolotlPlaintextMessage(Config.OMEMO_PADDING ? plaintext.trim() : plaintext, session.getFingerprint());

        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
                | InvalidAlgorithmParameterException | IllegalBlockSizeException
                | BadPaddingException | NoSuchProviderException e) {
            throw new CryptoFailedException(e);
        }
    }
    return plaintextMessage;
}
 
Example #25
Source File: DefaultCryptor.java    From juddi with Apache License 2.0 5 votes vote down vote up
public String decrypt(String str) throws NoSuchPaddingException,
     NoSuchAlgorithmException,
     InvalidAlgorithmParameterException,
     InvalidKeyException,
     IllegalBlockSizeException,
     BadPaddingException,
     UnsupportedEncodingException {
        byte[] encs = crypt(Cipher.DECRYPT_MODE, Base64.decodeBase64(str.getBytes("UTF-8")));
        return new String(encs, "UTF-8");
}
 
Example #26
Source File: EncryptionUtil.java    From jumbune with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static String getPlain(String encryptedText) {
	byte[] encryptedTextBytes = DatatypeConverter.parseBase64Binary(encryptedText);
    Cipher cipher;
    byte[] decryptedTextBytes = null;
	try {
		cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
       
    cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, new CustomKey());
    decryptedTextBytes = cipher.doFinal(encryptedTextBytes);
	} catch (NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException | InvalidKeyException e) {
		e.printStackTrace();
	}	    
    return new String(decryptedTextBytes);	
}
 
Example #27
Source File: EncryptionHelper.java    From andOTP with MIT License 5 votes vote down vote up
public static byte[] decrypt(SecretKey secretKey, IvParameterSpec iv, byte[] cipherText)
        throws NoSuchPaddingException, InvalidKeyException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException {
    Cipher cipher = Cipher.getInstance(Constants.ALGORITHM_SYMMETRIC);
    cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);

    return cipher.doFinal(cipherText);
}
 
Example #28
Source File: RSACore.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
/**
 * Parse the msg into a BigInteger and check against the modulus n.
 */
private static BigInteger parseMsg(byte[] msg, BigInteger n)
        throws BadPaddingException {
    BigInteger m = new BigInteger(1, msg);
    if (m.compareTo(n) >= 0) {
        throw new BadPaddingException("Message is larger than modulus");
    }
    return m;
}
 
Example #29
Source File: Common.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
     * Function to decrypt a private-key and return it from a Base64-encoded
     * key-handle (which has a 16-byte IV prepended to it)
     *
     * @param s String containing a 16-byte IV plus the encrypted keyhandle
     * @return String containing the Base64-encoded plaintext JSON structure of
     * the key-handle
     * @throws DecoderException
     * @throws NoSuchAlgorithmException
     * @throws NoSuchProviderException
     * @throws NoSuchPaddingException
     * @throws InvalidKeyException
     * @throws InvalidAlgorithmParameterException
     * @throws ShortBufferException
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     * @throws UnsupportedEncodingException
     * @throws InvalidKeySpecException
     * @throws SignatureException
     * @throws java.security.spec.InvalidParameterSpecException
     */
    public static String decryptKeyHandle(String s)
            throws DecoderException, NoSuchAlgorithmException,
            NoSuchProviderException, NoSuchPaddingException,
            InvalidKeyException, InvalidAlgorithmParameterException,
            ShortBufferException, IllegalBlockSizeException,
            BadPaddingException, UnsupportedEncodingException,
            InvalidKeySpecException, SignatureException,
            InvalidParameterSpecException
    {
        // Get wrapping key
        byte[] Seckeybytes = Hex.decodeHex(Constants.FIXED_AES256_WRAPPING_KEY.toCharArray());
        SecretKeySpec sks = new SecretKeySpec(Seckeybytes, "AES");

        // Decode IV + ciphertext and extract components into new arrays
        byte[] ctkhiv = Base64.getUrlDecoder().decode(s);
        byte[] iv = new byte[16];
//        System.out.println(s);
        byte[] ctkh = new byte[ctkhiv.length - iv.length];
        System.arraycopy(ctkhiv, 0, iv, 0, Constants.ENCRYPTION_MODE_CBC_IV_LENGTH);
        System.arraycopy(ctkhiv, Constants.ENCRYPTION_MODE_CBC_IV_LENGTH, ctkh, 0, ctkh.length);

        // Decrypt keyhandle using IV in input string
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BCFIPS");
        IvParameterSpec ivspec = new IvParameterSpec(iv);
        cipher.init(Cipher.DECRYPT_MODE, sks, ivspec);
        byte[] ptkh = new byte[cipher.getOutputSize(ctkh.length)];
        int p = cipher.update(ctkh, 0, ctkh.length, ptkh, 0);
        cipher.doFinal(ptkh, p);

        return new String(ptkh, "UTF-8");
    }
 
Example #30
Source File: UserStoreConfigXMLProcessor.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * Function to decrypt given cipher text
 *
 * @param propValue base64encoded ciphertext
 * @return plaintext
 * @throws NoSuchPaddingException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws org.wso2.micro.integrator.security.user.api.UserStoreException
 * @throws InvalidKeyException
 * @throws BadPaddingException
 * @throws IllegalBlockSizeException
 */
private String decryptProperty(String propValue)
        throws NoSuchPaddingException, NoSuchAlgorithmException, NoSuchProviderException,
        org.wso2.micro.integrator.security.user.api.UserStoreException, InvalidKeyException, BadPaddingException,
        IllegalBlockSizeException {

    Cipher keyStoreCipher;
    String cipherTransformation = System.getProperty(CIPHER_TRANSFORMATION_SYSTEM_PROPERTY);
    byte[] cipherTextBytes = Base64.decode(propValue.trim());

    privateKey = (privateKey == null) ? getPrivateKey() : privateKey;
    if (privateKey == null) {
        throw new org.wso2.micro.integrator.security.user.api.UserStoreException(
                "Private key initialization failed. Cannot decrypt the userstore password.");
    }

    if(cipherTransformation != null) {
        // extract the original cipher if custom transformation is used configured in carbon.properties.
        CipherHolder cipherHolder = cipherTextToCipherHolder(cipherTextBytes);
        if (cipherHolder != null) {
            // cipher with meta data.
            if (log.isDebugEnabled()) {
                log.debug("Cipher transformation for decryption : " + cipherHolder.getTransformation());
            }
            keyStoreCipher = Cipher.getInstance(cipherHolder.getTransformation(), "BC");
            cipherTextBytes = cipherHolder.getCipherBase64Decoded();
        } else {
            // If the ciphertext is not a self-contained, directly decrypt using transformation configured in
            // carbon.properties file
            keyStoreCipher = Cipher.getInstance(cipherTransformation, "BC");
        }
    } else {
        // If reach here, user have removed org.wso2.CipherTransformation property or carbon.properties file
        // hence RSA is considered as default transformation
        keyStoreCipher = Cipher.getInstance("RSA", "BC");
    }
    keyStoreCipher.init(Cipher.DECRYPT_MODE, privateKey);
    return new String(keyStoreCipher.doFinal(cipherTextBytes), Charset.defaultCharset());
}