[英]when i am decrypting ,i am not getting the proper plaintext
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)
從返回值重新創建String。
包括密鑰派生在內的所有事情也不是很好。 嘗試使用PBKDF2查找一些Java示例(此站點上應該有很多),並嘗試理解Java中的(字符)編碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.