【问题标题】:Encryption RC4 algorithm for integers整数的加密 RC4 算法
【发布时间】:2014-08-15 09:40:37
【问题描述】:

基本上我可以为Strings 成功实现RC4 算法,它为key 采用Byte[] 数组:

byte [] key = "AAAAA".getBytes("ASCII");

如果我将 clearText 作为 String 说“24”,那么密文范围非常高,比如 > 2000 。 但是对于我的算法,我需要将其限制在较小的范围内 ~200。

那么我可以为int 提供更好的选择吗?

这就是我对字符串所做的:

加密模式:

  byte [] key = "AAAAA".getBytes("ASCII");

  String clearText = "66";


  Cipher rc4 = Cipher.getInstance("RC4");
  SecretKeySpec rc4Key = new SecretKeySpec(key, "RC4");
  rc4.init(Cipher.ENCRYPT_MODE, rc4Key);
  byte [] cipherText = rc4.update(clearText.getBytes("ASCII"));

检查值:

      System.out.println("clear (ascii)        " + clearText);
      System.out.println("clear (hex)          " + DatatypeConverter.printHexBinary(clearText.getBytes("ASCII")));
      System.out.println("cipher (hex) is      " + DatatypeConverter.printHexBinary(cipherText));

- 可以对这些 类型执行任何技巧来获得较低的int 值吗?

解密

  Cipher rc4Decrypt = Cipher.getInstance("RC4");
  rc4Decrypt.init(Cipher.DECRYPT_MODE, rc4Key);
  byte [] clearText2 = rc4Decrypt.update(cipherText);

SSCCE

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
public class MyArcFour
{

  public static void main(String args[])throws Exception
    {


      byte [] key = "AAAAA".getBytes("ASCII");

      String clearText = "66";


      Cipher rc4 = Cipher.getInstance("RC4");
      SecretKeySpec rc4Key = new SecretKeySpec(key, "RC4");
      rc4.init(Cipher.ENCRYPT_MODE, rc4Key);

      byte [] cipherText = rc4.update(clearText.getBytes("ASCII"));

      System.out.println("clear (ascii)        " + clearText);
      System.out.println("clear (hex)          " + DatatypeConverter.printHexBinary(clearText.getBytes("ASCII")));
      System.out.println("cipher (hex) is      " + DatatypeConverter.printHexBinary(cipherText));


      Cipher rc4Decrypt = Cipher.getInstance("RC4");
      rc4Decrypt.init(Cipher.DECRYPT_MODE, rc4Key);
      byte [] clearText2 = rc4Decrypt.update(cipherText);

      System.out.println("decrypted (clear) is " + new String(clearText2, "ASCII"));
   }
}

【问题讨论】:

  • "那么密文范围很大,比如说>2000"这是什么意思?
  • @Duncan 我在加密后得到的结果字符串,如果你将它解析为 int,则很高

标签: java encryption rc4-cipher


【解决方案1】:

当使用 流密码(如 RC4 一样)时,密文的长度将始终等于明文的长度。

这意味着当您加密 int(有 4 个字节)时,您将始终收到另一个 int(4 个字节)作为加密输出。所以理论上当你加密0时,你可以得到2<sup>20</sup>的结果。
如果您想要0 - 255 范围内的值,您只能加密单个字节。

任何好的加密算法都必须满足以下属性:当使用相同的加密密钥k时,任何不同的明文p必须加密为不同的密文c
此属性仅在 size(output) &gt;= size(input) 时可用。

为什么一定要这样?
好吧,考虑下面的加密函数:

/* output = E(key, input); key = 123 */

i | o
======
1 | 17
2 | 13
3 | 17
4 | 125

那么当你有密文17 和密钥123 时,就无法判断最初加密的值是1 还是3

这意味着,如果您希望以后能够明确解密这些值,则无法减小生成的密文的大小。

如果不需要解密,您可以随时使用output % some_number 或使用具有所需输出长度的散列函数

【讨论】:

  • 它抛出 Exception that key must be > 40 bit :/
  • 密钥长度必须为&gt;= 40 位(5 bytesString with 5 characters)。 key = 123 只是假设加密函数的假设示例。
猜你喜欢
  • 2021-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多