2

I am looking for a symmetric key encryption scheme which would encrypt my 12 byte data. As you can see it does not conform to 64 bit or 128 bit boundaries for me to use block ciphering algorithms and I do not want to pad the data as I have restriction on the length of encrypted data. The restriction is because I would be transforming using base 32 it to a printable key which cannot exceed 20 chars. The plain text has very predictable data pattern, so the encryption scheme should be able to hide that. From what I understand, the pseudo random key generation is the only soultion fo this problem, but the solution that encrypts the data and solution that decrypts it, do not talk to each other.

4

3 回答 3

4

为什么不使用 RC4?密文与明文的大小完全相同 - 在您的情况下为 12 个字节。它带有 Java(5 或更高版本)。这是一个例子:

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 = "MYVERYINSECUREKEY".getBytes("ASCII");

      String clearText = "123456789012";

      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"));
   }
}

这会生成以下输出:

clear (ascii)        123456789012
clear (hex)          313233343536373839303132
cipher (hex) is      CBFB9A712E55EBD985C8F2DF
decrypted (clear) is 123456789012

当然,您可能希望使用比示例中更好(更长、更随机)的密钥。

于 2012-09-21T03:25:04.847 回答
1

您可以使用像 RC4 这样的流密码,但正如您所发现的,您不能重复使用密钥。对于流密码,使用键/随机数(随机数 = 使用一次的数字)组合。随机数可以像 1、2、3、4、... 或日期/时间一样简单,并且需要与密文一起存储。在随机数循环为零并开始重复之前更改密钥。如果您使用日期/时间,请确保时钟的滴答速度足够快,不会重复一个值。

你有一个长期密钥和一个随机数。每次你想加密某些东西时,对它们进行哈希处理以获得会话密钥:

sessionKey <- SHA256(longTermKey + nonce)

仅使用一次此会话密钥,然后将其丢弃。存储随机数以用于解密。增加一个数字随机数以备下次使用。对于日期/时间随机数,插入一个短暂的延迟以确保时钟已更改。下次使用时,nonce必须不同。

当您更改长期密钥时,您需要对所有数据进行解密和重新加密。或者为你的 nonce 选择一个大的比特大小,并保持你的长期密钥非常安全。

于 2012-09-21T12:20:29.047 回答
0

你想要/需要一个流密码:http ://en.wikipedia.org/wiki/Stream_cipher

于 2012-09-21T12:19:01.397 回答