import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.Security;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
public class SHAhashingexample
{
public static void main(String[] args)throws Exception
{
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
String usernametohash = "123456";
String salt="salty food";
String userdata="hello how are you!";
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update((usernametohash+salt).getBytes());
byte byteData[] = md.digest();
System.out.println("Digested value : " + byteData);
StringBuffer sb = new StringBuffer();
for (int i = 0; i < byteData.length; i++)
{
sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
}
System.out.println("Hash code value of username : " + sb);
byte[] actualkey=sb.toString().getBytes();
byte[] first_key = Arrays.copyOf(actualkey, 16);
Key key = new SecretKeySpec(first_key, "AES");
System.out.println("Derived AES key is "+key.toString());
SecureRandom random = new SecureRandom();
IvParameterSpec ivSpec = createCtrIvForAES(1, random);
Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding", "BC");
cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
byte[] cipherText = cipher.doFinal(userdata.getBytes());
System.out.println("ciphertext is : " + cipherText);
cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
byte[] plainText = cipher.doFinal(cipherText) ;
System.out.println("plaintext is : " + plainText);
}
public static IvParameterSpec createCtrIvForAES(int messageNumber, SecureRandom random)
{
byte[] ivBytes = new byte[16];
random.nextBytes(ivBytes);
for (int i = 0; i < 16; i++)
{
ivBytes[i] = 0;
}
return new IvParameterSpec(ivBytes);
}
}
我的目的是从用户名哈希和硬编码随机数算法 SHA-256 和 AES CTR 模式中派生 aes 128 位密钥。想使用 SHA-256 算法生成用户名哈希。我觉得我们需要 IV 才能与 CTR 模式一起使用,初始化向量的值应该是多少,我只是猜测全是零...
你在这里做错了很多事情,但你的实际问题是你忘记使用 new String(plainText)
从返回的值重新创建一个字符串。
密钥派生在内的所有内容也不好。尝试使用PBKDF2找到一些Java示例(这个站点上应该有很多),并尝试理解Java中的(字符)编码。