- 接上文,AES的密钥长度再底层定义了固定的长度,16,24,32.但是再实际生产情况下,可能会出现比较任意长度的密钥,如何处理?
- 在获取加解密对象的时候特殊处理:
import com.yutu.pwd.util.HexUtils;
import org.junit.jupiter.api.Test;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
public class AESTest {
private static final String UTF8 = StandardCharsets.UTF_8.name();
private static final String ALGORITHM = "AES";
private static final String KEY = "12345678abcdefghss";
@Test
public void S() throws Exception{
String str = "小汪学java";
String encrypt = encrypt(str);
System.out.println("16进制 + Aes 加密后的字符串: " + encrypt);
System.out.println("------------------------");
String decrypt = decrypt(encrypt);
System.out.println("16进制 + Aes 解密后的字符串: " + decrypt);
}
private String encrypt(String text) throws Exception{
Cipher cipher = getCipher2(Cipher.ENCRYPT_MODE, KEY);
byte[] encodedBytes = cipher.doFinal(text.getBytes(UTF8));
return HexUtils.covertBytes2HexStr(encodedBytes);
}
private String decrypt(String encodedStr) throws Exception{
byte[] bytes = HexUtils.convertHex2Bytes(encodedStr);
Cipher cipher = getCipher2(Cipher.ENCRYPT_MODE, KEY);
SecretKey secretKey = new SecretKeySpec(KEY.getBytes(UTF8), ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE,secretKey);
byte[] decryptBytes = cipher.doFinal(bytes);
return new String(decryptBytes,UTF8);
}
private Cipher getCipher(int type,String seed) throws Exception{
Cipher cipher = Cipher.getInstance(ALGORITHM);
SecretKey secretKey = new SecretKeySpec(seed.getBytes(UTF8), ALGORITHM);
cipher.init(type,secretKey);
return cipher;
}
private Cipher getCipher2(int type,String seed) throws Exception{
Cipher cipher = Cipher.getInstance(ALGORITHM);
KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(seed.getBytes(UTF8));
keyGenerator.init(128,secureRandom);
SecretKey secretKey = keyGenerator.generateKey();
byte[] encoded = secretKey.getEncoded();
SecretKey secretKeySpec = new SecretKeySpec(encoded, ALGORITHM);
cipher.init(type,secretKeySpec);
return cipher;
}
}