【问题标题】:JAVA ANDROID AES CFB NOPADDINGJAVA ANDROID AES CFB NOPADDING
【发布时间】:2015-12-29 11:34:13
【问题描述】:

我创建了一个 Java 文件,其中包含以下加密或解密字符串的代码:

public class Aes {
public static String encrypt(String seed, String cleartext)
        throws Exception {
    byte[] rawKey = getRawKey(seed.getBytes());
    byte[] result = encrypt(rawKey, cleartext.getBytes());
    return toHex(result);
}

public static String decrypt(String seed, String encrypted)
        throws Exception {
    byte[] rawKey = getRawKey(seed.getBytes());
    byte[] enc = toByte(encrypted);
    byte[] result = decrypt(rawKey, enc);
    return new String(result);
}

private static byte[] getRawKey(byte[] seed) throws Exception {
    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
    sr.setSeed(seed);
    kgen.init(128, sr); // 192 and 256 bits may not be available
    SecretKey skey = kgen.generateKey();
    byte[] raw = skey.getEncoded();
    return raw;
}

private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
    byte[] iv = new byte[] { 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF }; 
    IvParameterSpec ivSpec = new IvParameterSpec(iv);

    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
    Cipher cipher = Cipher.getInstance("AES/CFB/NoPadding");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivSpec);
    byte[] encrypted = cipher.doFinal(clear);
    return encrypted;
}

private static byte[] decrypt(byte[] raw, byte[] encrypted)
        throws Exception {
    byte[] iv = new byte[] { 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF }; 
    IvParameterSpec ivSpec = new IvParameterSpec(iv);

    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
    Cipher cipher = Cipher.getInstance("AES/CFB/NoPadding");
    cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivSpec);
    byte[] decrypted = cipher.doFinal(encrypted);
    return decrypted;
}

public static String toHex(String txt) {
    return toHex(txt.getBytes());
}

public static String fromHex(String hex) {
    return new String(toByte(hex));
}

public static byte[] toByte(String hexString) {
    int len = hexString.length() / 2;
    byte[] result = new byte[len];
    for (int i = 0; i < len; i++)
        result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2),
                16).byteValue();
    return result;
}

public static String toHex(byte[] buf) {
    if (buf == null)
        return "";
    StringBuffer result = new StringBuffer(2 * buf.length);
    for (int i = 0; i < buf.length; i++) {
        appendHex(result, buf[i]);
    }
    return result.toString();
}

private final static String HEX = "0123456789ABCDEF";

private static void appendHex(StringBuffer sb, byte b) {
    sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
}
}

我已经成功尝试加密一个字符串,但没有解密它......请帮助我。这是我之前测试过的加密示例代码:

String data = "HELP";
String enc = "";
try {
enc = Aes.encrypt("1234567890", data);
Log.i("ENCRYPT", data + " TO " + enc);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

结果是:48F1880B

我的问题是,如何解密它?我使用上面的代码进行了测试,但结果不等于明文!请帮帮我...

【问题讨论】:

  • 这是包含此缺陷getRawKey(..)implementation 的第二个问题。你们都是从哪里得到这么糟糕的代码的?
  • 我是从网上弄来的,试着修复一下,我只是举个例子,但是我没有找到一个很好的例子,用aes cfb模式加密和解密,请帮助我:(跨度>
  • 我从这个链接得到:stackoverflow.com/questions/11418336/…
  • owlstead 对那个问题的回答已经表明代码很糟糕——你为什么还要接受它?
  • 很抱歉,通过从互联网上复制粘贴随机代码示例来编写安全代码是不可能的。

标签: java android encryption cryptography aes


【解决方案1】:

以下示例类应该为您提供有关如何正确加密/解密的很好的参考,并标记了所有步骤:

public class AES {

    public static SecretKey generateAESKey(int bits) throws NoSuchAlgorithmException{
        //This method is provided as to securely generate a AES key of the given length.

        //In practice you can specify your own SecureRandom instance.
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(bits);
        return kgen.generateKey();
    }

    public static byte[] encrypt(SecretKey key, byte[] plaintext) throws Exception{
        //In practice you should specify your SecureRandom implementation.
        SecureRandom rnd = new SecureRandom();

        //Generate random IV of 128-bit (AES block size)
        byte[] IV = new byte[128 / 8]; 
        rnd.nextBytes(IV);
        IvParameterSpec IVSpec = new IvParameterSpec(IV);

        //Create the cipher object to perform AES operations.
        //Specify Advanced Encryption Standard - Cipher Feedback Mode - No Padding
        Cipher AESCipher = Cipher.getInstance("AES/CFB/NoPadding");

        //Initialize the Cipher with the key and initialization vector.
        AESCipher.init(Cipher.ENCRYPT_MODE, key, IVSpec);

        //Encrypts the plaintext data
        byte[] ciphertext = AESCipher.doFinal(plaintext);

       /*
        * The IV must now be transferred with the ciphertext somehow. The easiest 
        * way to accomplish this would be to prepend the IV to the ciphertext 
        * message.
        */

        //Allocate new array to hold ciphertext + IV
        byte[] output = new byte[ciphertext.length + (128 / 8)];

        //Copy the respective parts into the array.
        System.arraycopy(IV, 0, output, 0, IV.length);
        System.arraycopy(ciphertext, 0, output, IV.length, ciphertext.length);

        return output;
    }

    public static byte[] decrypt(SecretKey key, byte[] IV, byte[] ciphertext) throws Exception{
        //Create the cipher object to perform AES operations.
        //Specify Advanced Encryption Standard - Cipher Feedback Mode - No Padding
        Cipher AESCipher = Cipher.getInstance("AES/CFB/NoPadding");

        //Create the IvParameterSpec object from the raw IV
        IvParameterSpec IVSpec = new IvParameterSpec(IV);

        //Initialize the Cipher with the key and initialization vector.
        AESCipher.init(Cipher.DECRYPT_MODE, key, IVSpec);

        //Decrypts the ciphertext data
        byte[] plaintext = AESCipher.doFinal(ciphertext);

        return plaintext;
    }

    public static void main(String[] args) throws Exception{
        //Demo the program

        String sPlaintext = "rainbows"; //String plaintext
        byte[] rPlaintext = sPlaintext.getBytes(Charset.forName("UTF-8")); //Raw byte array plaintext

        //We first need to generate a key of 128-bit
        SecretKey key = generateAESKey(128);

        //Encrypt the plaintext
        byte[] output = encrypt(key, rPlaintext);

        // ----------------- //

        //Extract the IV from the encryption output
        byte[] IV = new byte[128 / 8];
        byte[] ciphertext = new byte[output.length - (128 / 8)];

        System.arraycopy(output, 0, IV, 0, IV.length);
        System.arraycopy(output, IV.length, ciphertext, 0, ciphertext.length);

        //Decrypt the ciphertext
        byte[] dPlaintext = decrypt(key, IV, ciphertext);

        String decryptedMessage = new String(dPlaintext, Charset.forName("UTF-8"));

        //Print stuff out
        System.out.println("Original message: " + sPlaintext);
        System.out.println("Original message bytes: " + Arrays.toString(rPlaintext));
        System.out.println("Encryption Output bytes: " + Arrays.toString(output));
        System.out.println("Decrypted message bytes: " + Arrays.toString(dPlaintext));
        System.out.println("Decrypted message: " + decryptedMessage);
    }
}

不过有几点需要注意:

throws Exception

不可接受。这只是为了简化代码而放置的,不应该在实践中使用。虽然像NoSuchAlgorithmException 这样的一些检查异常不太可能被抛出,但请注意decrypt() 方法会因解密失败(即错误的密钥/IV/密文)抛出异常。 p>

进入我的下一点,您不应该依赖decrypt() 方法抛出异常来验证输入。这应该是一个安全的单向哈希函数,例如SHA-2

注意加密/解密密钥是如何生成一次的。 AES 是一种对称分组密码,这意味着加密和解密都使用相同的密钥。请注意这一点,不要在加密和解密之间生成新密钥(不过,如果您愿意,您可以在每次加密时生成一个新密钥,只要您使用相同的密钥进行解密)。

【讨论】:

    【解决方案2】:

    问题主要出在

    public static String toHex(String txt) {
    return toHex(txt.getBytes());
    }
    
    public static String fromHex(String hex) {
    return new String(toByte(hex));
    }
    
    public static byte[] toByte(String hexString) {
    int len = hexString.length() / 2;
    byte[] result = new byte[len];
    for (int i = 0; i < len; i++)
        result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2),
                16).byteValue();
    return result;
    

    在从 Hex String 转换 String 时,您不会使用前导零转换它们,即当您转换 char 并且该字符的可能值为零时,十六进制值也是 00 ,默认情况下,您的方法只是忽略一个零,并且只将一个零添加到十六进制字符串

    注意:-数字零0不等于十六进制值零。十六进制值零是空字符,参考ASCII表。

    前导零 ef1b0030ef 没有前导零 ef1b030ef

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-30
      • 2015-06-18
      • 1970-01-01
      • 2019-02-15
      • 1970-01-01
      • 1970-01-01
      • 2016-11-14
      相关资源
      最近更新 更多