📄 aes.java
字号:
/*
* AES.java
*
* Created on 2007年12月21日, 下午7:01
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.SecretKeySpec;
/**
*
* @author deadknight
*/
public class AES {
/** Creates a new instance of AES */
public AES() {}
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException, IllegalBlockSizeException, BadPaddingException, InvalidKeySpecException
{
String test = "gohome never BACK!";
String aeskey = "1234567890abcdef";
byte plain[] = test.getBytes();
// byte k[] = AES.getKey();
byte k[] = aeskey.getBytes();
byte c[] = AES.encrpyt(plain,k);
byte p[] = AES.decrpyt(c,k);
System.out.println(new String (c)) ;
System.out.println(new String (p));
}
public static byte[] getKey()
{
byte[] raw = null;
try
{
BigInteger aesKeyBigInteger = new BigInteger("C5F9D65AEB7165562E38CE328108167A",16);
KeyGenerator kg = KeyGenerator.getInstance("AES");
kg.init(128, new SecureRandom(aesKeyBigInteger.toString().getBytes()));
SecretKey skey = kg.generateKey();
raw = skey.getEncoded();
// System.out.println(raw);
String keyString = "[B@16f8cd0";
byte rawString [] = keyString.getBytes();
}catch(Exception ex)
{
ex.printStackTrace();
}
return raw;
}
public static byte[] encrpyt(byte plaintext[], byte keyBytes[])
{
byte[] cipher = null;
try
{
Key key = new SecretKeySpec(keyBytes,"AES");
Cipher enCipher = Cipher.getInstance("AES");
enCipher.init(Cipher.ENCRYPT_MODE,key);
cipher = enCipher.doFinal(plaintext);
}catch(Exception ex)
{
ex.printStackTrace();
}
return cipher;
}
public static byte[] decrpyt(byte ciphertext[], byte keyBytes[])
{
byte[] plain = null;
try
{
Key key = new SecretKeySpec(keyBytes,"AES");
Cipher deCipher = Cipher.getInstance("AES");
deCipher.init(Cipher.DECRYPT_MODE,key);
plain = deCipher.doFinal(ciphertext);
}catch(Exception ex)
{
ex.printStackTrace();
}
return plain;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -