【问题标题】:How to encrypt arbitrary data types using BouncyCastle?如何使用 BouncyCastle 加密任意数据类型?
【发布时间】:2013-09-19 15:18:49
【问题描述】:

谁能告诉我一个例子,说明如何使用 BouncyCastle(或类似 API)在 Java 中对String 以外的数据类型进行加密?

我想加密其他 Java 类型,例如 IntegerDoubleDate 等。我查看了 bouncycastle.org,但找不到任何有关其 API 的文档。

【问题讨论】:

标签: java encryption bouncycastle


【解决方案1】:

加密是始终对二进制数据执行的操作。您看到的任何使用 String 对象的示例都会在此过程中的某个时间点将这些字符串转换为字节数组。

目标是定义将数据转换为字节数组表示的规范方法。一旦你有了这个,你就可以使用在互联网上找到的示例代码来执行加密。

例如,您可能希望将Integer 转换为四字节数组。也许使用如下代码:

ByteBuffer.allocate(4).putInt(integerValue).array()

Date 最好转换为 UNIX 时间戳,然后使用上面的代码转换为字节数组。

您的加密数据的接收者必须了解您如何将其序列化为字节数组,以便他们可以反转该过程。请注意,在字符串的情况下,重要的是双方在转换到/从字节数组时使用的字符集达成一致。

【讨论】:

    【解决方案2】:

    我可以给你加密字节数组的代码,希望对你有所帮助。请记住,下面的 ENCRYPTION_KEY 值可以是任何值,这完全取决于您。

     // Cryptographic algorithm
      private final String ALGORITHM = "AES";
      //
     private final byte[] ENCRYPTION_KEY = new byte[]
     {
            'E', 'r', ';', '|', '<', '@', 'p', 'p', 'l', '1', 'c', '@', 't', '1', '0', 'n'
     };
    
    public byte[] encryptValue(byte[] valueToEnc) throws EncryptionException
    {
        try
        {
            // Constructs a secret key from the given byte array and algorithm
            Key key = new SecretKeySpec(ENCRYPTION_KEY, ALGORITHM);
            // Creating Cipher object by calling getInstance() factory methods and
            // passing ALGORITHIM VALUE = "AES" which is a 128-bit block cipher
            // supporting keys of 128, 192, and 256 bits.
            Cipher c = Cipher.getInstance(ALGORITHM);
            // Initialize a Cipher object with Encryption Mode and generated key
            c.init(Cipher.ENCRYPT_MODE, key);
            // To encrypt data in a single step, calling doFinal() methods: If we
            // want to encrypt data in multiple steps, then need to call update()
            // methods instead of doFinal()
            byte[] encValue = c.doFinal(valueToEnc);
            // Encrypting value using Apache Base64().encode method
            byte[] encryptedByteValue = new Base64().encode(encValue);
    
            return encryptedByteValue;
        }
        catch (Exception e)
        {
            throw new EncryptionException(e.getMessage(), e);
        }
    }
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-27
      • 2022-07-23
      • 1970-01-01
      • 2017-03-17
      • 1970-01-01
      • 2013-01-13
      • 2014-03-01
      • 1970-01-01
      相关资源
      最近更新 更多