Java逐字加密

时间:2012-07-27 08:12:48

标签: java encryption aes

我正在尝试接受一个长字符串并使用以下代码对其进行加密:

import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.io.*;

public class AESEncrypt {

    /**
     * Turns array of bytes into string
     * 
     * @param buf
     *            Array of bytes to convert to hex string
     * @return Generated hex string
     */
    public static String asHex(byte buf[]) {
        StringBuffer strbuf = new StringBuffer(buf.length * 2);
        int i;

        for (i = 0; i < buf.length; i++) {
            if (((int) buf[i] & 0xff) < 0x10)
                strbuf.append("0");

            strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
        }

        return strbuf.toString();
    }

    public static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character
                    .digit(s.charAt(i + 1), 16));
        }
        return data;
    }

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

        String message = "Test text!";

        // Get the KeyGenerator
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128); // 192 and 256 bits may not be available

        // Generate the secret key specs.
        SecretKey skey = kgen.generateKey();
        byte[] raw = skey.getEncoded();

        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        System.out.println("Key: " + asHex(raw));

        // Instantiate the cipher

        Cipher cipher = Cipher.getInstance("AES");

        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

        byte[] encrypted = cipher.doFinal((args.length == 0 ? message : args[0]).getBytes());
        System.out.println("encrypted string: " + asHex(encrypted));

    }
}

但是,我想逐字加密并打印出加密文本:

原始字符串 - &gt;测试文字!

加密字符串 - &gt; 29f84h2f 23f9f92jf3

我在网上找不到任何可以帮助我的例子。无论如何我能做到这一点吗?

2 个答案:

答案 0 :(得分:0)

AES是一个块密码,它使用16字节块。它不是单词,而是固定块。如果您想将文本拆分为不同大小的单词,那么您可能会使用流式密码(如RC4)或者在CTR模式下使用AES来更接近您的需求,从而有效地将AES转换为流密码。流密码不能在块中工作,而是以字节为单位。您可以从流中取出3个字节,以获得3个字母的单词,或者从流中取出9个字节,以获得9个字母的单词。

你需要弄清楚如何处理单词之间的空格,标点符号等。您还需要考虑重新键入密码的频率。你想为每个单词重新键入,还是只在每个字符串的开头重新键入?与任何流密码一样,永远不要使用相同的密钥两次。

答案 1 :(得分:0)

尝试以下示例;实际上,它只需要使用StringTokenizer。首先,您必须为目标字符串添加令牌。之后,加密令牌字符串。

import java.util.StringTokenizer;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;


public class AES {
    public static String asHex(byte[] buf) {
        StringBuffer strbuf = new StringBuffer(buf.length * 2);
        int i;

        for (i = 0; i < buf.length; i++) {
            if (((int)buf[i] & 0xff) < 0x10)
                strbuf.append("0");
            strbuf.append(Long.toString((int)buf[i] & 0xff, 16));
        }

        return strbuf.toString();
    }

    public static void main(String[] args) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128); // 192 and 256 bits may not be available
        // Generate the secret key specs.
        SecretKey skey = kgen.generateKey();
        byte[] raw = skey.getEncoded();

        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

        String target = "This is just an example";
        StringTokenizer token = new StringTokenizer(target);
        while(token.hasMoreTokens()) {
            String temp = token.nextToken();
            byte[] encrypted = cipher.doFinal((args.length == 0 ?  temp : args[0]).getBytes());
            System.out.println(asHex(encrypted) + " ");
        }
    }
}

输出:

    d40186eab04d10e299801e7ad9046c06 6a71265c768a3b6e1f1a8f891d621c1d 735e3f54c8ad7242466e3517e8dd1659 5216643345db0f0c12f65c66c5363be3 b823355d5bb31bf092df98e18fa8001c