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 Project: protools   Author: SeanDragon   File: ToolElGamal.java    License: 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 #2
Source Project: jdk8u60   Author: chenghanpeng   File: RSAPadding.java    License: 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 #3
Source Project: protect   Author: jasonkresch   File: LocalChannelSender.java    License: 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 #4
Source Project: ripple-lib-java   Author: ripple-unmaintained   File: McElieceKobaraImaiCipherSpi.java    License: 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 #5
Source Project: openjdk-jdk8u-backup   Author: AdoptOpenJDK   File: CipherCore.java    License: 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 #6
Source Project: onboard   Author: sercxtyf   File: DataCipher.java    License: 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 Project: openjdk-jdk8u-backup   Author: AdoptOpenJDK   File: CipherInputStream.java    License: 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 #8
Source Project: jdk8u_jdk   Author: JetBrains   File: CipherCore.java    License: 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 #9
Source Project: mollyim-android   Author: mollyim   File: LogFile.java    License: 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 #10
Source Project: mollyim-android   Author: mollyim   File: KeyStoreHelper.java    License: 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 #11
Source Project: gsc-core   Author: gscsocial   File: Wallet.java    License: 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 #12
Source Project: bop-bitcoin-client   Author: bitsofproof   File: ExtendedKey.java    License: 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 #13
Source Project: dragonwell8_jdk   Author: alibaba   File: RSAPadding.java    License: 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 #14
Source Project: dragonwell8_jdk   Author: alibaba   File: CipherNCFuncTest.java    License: 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 #15
Source Project: j2objc   Author: google   File: CipherInputStream.java    License: 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 #16
Source Project: takes   Author: yegor256   File: CcAes.java    License: 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 #17
Source Project: dragonwell8_jdk   Author: alibaba   File: CipherWithWrappingSpi.java    License: 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 #18
Source Project: dragonwell8_jdk   Author: alibaba   File: TestCipher.java    License: 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 #19
Source Project: cassandra-reaper   Author: thelastpickle   File: SymmetricCryptograph.java    License: 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 #20
Source Project: spring-data-mongodb-encrypt   Author: bolcom   File: CryptVault.java    License: 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 #21
Source Project: BlockchainWallet-Crypto   Author: QuincySx   File: KeyStore.java    License: 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 #22
Source Project: azure-keyvault-java   Author: Azure   File: AesCbcHmacSha2.java    License: 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 #23
Source Project: jdk8u-jdk   Author: lambdalab-mirror   File: RSAPadding.java    License: 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 #24
Source Project: hottub   Author: dsrg-uoft   File: CipherWithWrappingSpi.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Unwrap a previously wrapped key.
 *
 * @param wrappedKey the key to be unwrapped.
 *
 * @param wrappedKeyAlgorithm the algorithm the wrapped key is for.
 *
 * @param wrappedKeyType the type of the wrapped key.
 * This is one of <code>Cipher.SECRET_KEY</code>,
 * <code>Cipher.PRIVATE_KEY</code>, or <code>Cipher.PUBLIC_KEY</code>.
 *
 * @return the unwrapped key.
 *
 * @exception InvalidKeyException if <code>wrappedKey</code> does not
 * represent a wrapped key, or if the algorithm associated with the
 * wrapped key is different from <code>wrappedKeyAlgorithm</code>
 * and/or its key type is different from <code>wrappedKeyType</code>.
 *
 * @exception NoSuchAlgorithmException if no installed providers
 * can create keys for the <code>wrappedKeyAlgorithm</code>.
 */
protected final Key engineUnwrap(byte[] wrappedKey,
                                 String wrappedKeyAlgorithm,
                                 int wrappedKeyType)
    throws InvalidKeyException, NoSuchAlgorithmException
{
    byte[] encodedKey;
    Key result = null;

    try {
        encodedKey = engineDoFinal(wrappedKey, 0,
                                   wrappedKey.length);
    } catch (BadPaddingException ePadding) {
        throw new InvalidKeyException();
    } catch (IllegalBlockSizeException eBlockSize) {
        throw new InvalidKeyException();
    }

    switch (wrappedKeyType) {
    case Cipher.SECRET_KEY:
        result = constructSecretKey(encodedKey,
                                    wrappedKeyAlgorithm);
        break;
    case Cipher.PRIVATE_KEY:
        result = constructPrivateKey(encodedKey,
                                     wrappedKeyAlgorithm);
        break;
    case Cipher.PUBLIC_KEY:
        result = constructPublicKey(encodedKey,
                                    wrappedKeyAlgorithm);
        break;
    }

    return result;

}
 
Example #25
Source Project: jumbune   Author: Impetus   File: EncryptionUtil.java    License: 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 #26
Source Project: Conversations   Author: iNPUTmice   File: XmppAxolotlMessage.java    License: 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 #27
Source Project: lucene-solr   Author: apache   File: CryptoKeys.java    License: Apache License 2.0 5 votes vote down vote up
public static byte[] decryptRSA(byte[] buffer, PublicKey pubKey) throws InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
  Cipher rsaCipher;
  try {
    rsaCipher = Cipher.getInstance("RSA/ECB/nopadding");
  } catch (Exception e) {
    throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,e);
  }
  rsaCipher.init(Cipher.DECRYPT_MODE, pubKey);
  return rsaCipher.doFinal(buffer, 0, buffer.length);
}
 
Example #28
Source Project: dragonwell8_jdk   Author: alibaba   File: TestSealedObjectNull.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException,
        IllegalBlockSizeException, ClassNotFoundException,
        BadPaddingException {
    Cipher nullCipher = new NullCipher();

    // Seal
    SealedObject so = new SealedObject(SEAL_STR, nullCipher);

    // Unseal and compare
    if (!(SEAL_STR.equals(so.getObject(nullCipher)))) {
        throw new RuntimeException("Unseal and compare failed.");
    }

    System.out.println("Test passed.");
}
 
Example #29
Source Project: fido2   Author: StrongKey   File: Common.java    License: 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 Project: AESCipher-Java   Author: WelkinXie   File: AESCipher.java    License: MIT License 5 votes vote down vote up
public static String aesEncryptString(String content, String key) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
	byte[] contentBytes = content.getBytes(charset);
	byte[] keyBytes = key.getBytes(charset);
	byte[] encryptedBytes = aesEncryptBytes(contentBytes, keyBytes);
	Encoder encoder = Base64.getEncoder();
    return encoder.encodeToString(encryptedBytes);
}