类javax.crypto.BadPaddingException源码实例Demo

下面列出了怎么用javax.crypto.BadPaddingException的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: protools   文件: ToolElGamal.java
/**
 * 用公钥加密
 *
 * @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);
}
 
源代码2 项目: jdk8u60   文件: RSAPadding.java
/**
 * 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();
    }
}
 
源代码3 项目: protect   文件: LocalChannelSender.java
/**
 * 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();
			}
		}
	}

}
 
/**
 * 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;
}
 
源代码5 项目: openjdk-jdk8u-backup   文件: CipherCore.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).
 */
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;
}
 
源代码6 项目: onboard   文件: DataCipher.java
/**
 * 解密方法
 * 
 */
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;
}
 
源代码7 项目: openjdk-jdk8u-backup   文件: CipherInputStream.java
/**
 * 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;
}
 
源代码8 项目: jdk8u_jdk   文件: CipherCore.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).
 */
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;
}
 
源代码9 项目: mollyim-android   文件: LogFile.java
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);
  }
}
 
源代码10 项目: mollyim-android   文件: KeyStoreHelper.java
@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);
  }
}
 
源代码11 项目: gsc-core   文件: Wallet.java
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);
    }
}
 
源代码12 项目: bop-bitcoin-client   文件: ExtendedKey.java
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);
	}
}
 
源代码13 项目: dragonwell8_jdk   文件: RSAPadding.java
/**
 * 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();
    }
}
 
源代码14 项目: dragonwell8_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");
    }
}
 
源代码15 项目: j2objc   文件: CipherInputStream.java
/**
 * 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;
}
 
源代码16 项目: takes   文件: CcAes.java
/**
 * 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);
    }
}
 
源代码17 项目: dragonwell8_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;
}
 
源代码18 项目: dragonwell8_jdk   文件: TestCipher.java
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;
                }
            }
        }
    }
}
 
源代码19 项目: cassandra-reaper   文件: SymmetricCryptograph.java
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);
}
 
源代码20 项目: spring-data-mongodb-encrypt   文件: CryptVault.java
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);
    }
}
 
源代码21 项目: BlockchainWallet-Crypto   文件: KeyStore.java
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);
    }
}
 
源代码22 项目: azure-keyvault-java   文件: AesCbcHmacSha2.java
@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);
}
 
源代码23 项目: jdk8u-jdk   文件: RSAPadding.java
/**
 * 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
            }
        }
    }
}
 
源代码24 项目: hottub   文件: CipherWithWrappingSpi.java
/**
 * 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;

}
 
源代码25 项目: jumbune   文件: EncryptionUtil.java
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);	
}
 
源代码26 项目: Conversations   文件: XmppAxolotlMessage.java
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;
}
 
源代码27 项目: lucene-solr   文件: CryptoKeys.java
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);
}
 
源代码28 项目: dragonwell8_jdk   文件: TestSealedObjectNull.java
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.");
}
 
源代码29 项目: fido2   文件: Common.java
/**
     * 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");
    }
 
源代码30 项目: AESCipher-Java   文件: AESCipher.java
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);
}