0
import java.io.*;
import java.security.MessageDigest;
import java.security.Security;
import java.util.Arrays;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class NewKey{
public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    String username = "username@teleparadigm.org";
    String userdata = "depression"+" "+"headache";
    // Get the Key
    byte[] key = (username).getBytes();
    MessageDigest sha = MessageDigest.getInstance("SHA-256");
    key = sha.digest(key);
    key = Arrays.copyOf(key, 16); 

    SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");    
    System.out.println("key used is "+username);
    System.out.println("encrypted key used is "+key);


    Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding", "BC");
    final byte[] IV = {-85, -67, -5, 88, 28, 49, 49, 85,114, 83, -40, 119, -65, 91, 76, 108};// Hard coded for now
    final IvParameterSpec ivSpec = new IvParameterSpec(IV);

    System.out.println("Derived AES key is: " +secretKeySpec.toString().getBytes().length );

    cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec,ivSpec);
    byte[] encrypted = cipher.doFinal((userdata).getBytes());                                              
    System.out.println("encrypted userdata: " + encrypted);

    cipher.init(Cipher.DECRYPT_MODE, secretKeySpec,ivSpec);
    byte[] original = cipher.doFinal(encrypted);
    String originalString = new String(original);
    System.out.println("Original userdata: " + originalString );
}
}

我已经为初始化向量(IV)使用了一些值,并且想知道使用 AES CTR 模式的正确方法是什么?

key = Arrays.copyOf(key, 16);

上述声明的目的是什么?建议我进行一些更改以增强程序。

4

1 回答 1

0

正确的方法是生成一个随机 NONCE(IvParameterSpecJava 使用它,但它实际上是一个 NONCE)并将其与密文一起发送。您应该使用 PBKDF2 来派生密码,并且您不应该使用getBytes()new String(byte[])因为它使用平台的默认编码而不是明确定义的编码。

于 2012-04-17T20:11:54.237 回答