使用Bouncy Castle提供程序进行AES加密/解密 [英] AES encrypt/decrypt with Bouncy Castle provider

查看:139
本文介绍了使用Bouncy Castle提供程序进行AES加密/解密的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我使用JDK 5的本机库开发的AES 256加密和解密的实现:

Here is my implementation of a AES 256 encrypt and decrypt, developed with the native library of JDK 5:

public static String encrypt(String key, String toEncrypt) throws Exception {
    Key skeySpec = generateKeySpec(key);
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    byte[] encrypted = cipher.doFinal(toEncrypt.getBytes());
    byte[] encryptedValue = Base64.encodeBase64(encrypted);
    return new String(encryptedValue);
}

public static String decrypt(String key, String encrypted) throws Exception {
    Key skeySpec = generateKeySpec(key);
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, skeySpec);
    byte[] decodedBytes = Base64.decodeBase64(encrypted.getBytes());
    byte[] original = cipher.doFinal(decodedBytes);
    return new String(original);
}

我想用Boucy Castle API(Java)实现相同的方法:我搜索了很多东西,测试了很多东西,没有结果……有人可以帮助我吗?

I want to implement the same methods with the Boucy Castle API (Java): I've searched a lot, tested a lot, without results ... can someone help me?

谢谢

推荐答案

您可以使用

Security.addProvider(new BouncyCastleProvider());
Cipher cipher = Cipher.getInstance("AES", "BC");

否则

Cipher cipher = Cipher.getInstance("AES", new BouncyCastleProvider());

也就是说, Cipher.getInstance( AES)使用不安全的电子密码本。您需要加密块链接( Cipher.getInstance( AES / CBC / PKCS5Padding))或计数器( Cipher.getInstance( AES / CTR / NoPadding))模式;它们都是安全的,主要区别在于CBC需要填充,而CTR则不需要。

That said, Cipher.getInstance("AES") uses Electronic Codebook, which is insecure. You either want Cipher Block Chaining (Cipher.getInstance("AES/CBC/PKCS5Padding")) or Counter (Cipher.getInstance("AES/CTR/NoPadding")) modes; they are both secure, the primary difference being that CBC requires padding while CTR does not.

这篇关于使用Bouncy Castle提供程序进行AES加密/解密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆