简介
随着软硬件技术的发展,多核CPU、分布式计算、量子计算机等理论的出现,DES在穷举方式的暴力攻击下还是相当脆弱的,因此很多人想办法用某种算法替代它,于是有了AES算法。尽管在AES之前,还有3DES,但是3DES效率非常低下。AES叫高级加密标准,该标准是美国国家标准技术研究所于2001年颁布的。AES旨在取代DES成为广泛使用的标准,2006年成为最流行的对称加密算法。AES分组大小为128位,密钥长度为128、192、256bit。最简单最常用的也就是128bit的秘钥。原理较为复杂但代码实现较为简单,主需要把密码设置为16字节,然后将DES算法实现的java代码中,将DES修改为AES即可。
import javax.crypto.*; import javax.crypto.spec.SecretKeySpec; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; public class AesDemo { public static void main(String[] args) { /** * 1.明文 * 2.提供原始秘钥 长度64位,8个字节 */ String clearText ="hello"; String originKey ="12345678"; try { String cipherText = desEncrpt(clearText,originKey); System.out.println(cipherText); String clearText2 =desDecrpt(cipherText,originKey); System.out.println(clearText2); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } } private static String desDecrpt(String cipherText, String originKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { //获取加密类对象 Cipher cipher =Cipher.getInstance("aes"); SecretKey key =getKey(originKey); //对加密类对象进行初始化 //mode:加密/解密 //key:对原始秘钥处理之后的秘钥 cipher.init(Cipher.DECRYPT_MODE,key); byte[] decodebytes =Base64.decode(cipherText); //使用加密工具类对象对明文进行解密 变成明文 byte[] doFinal= cipher.doFinal(decodebytes); // String encodetext =Base64.encode(doFinal); return new String(doFinal); } /** * 用DES算法进行加密 * ciper * @param clearText * @param originKey * 就是通过对比特为进行数学运算 * @return */ private static String desEncrpt(String clearText, String originKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { //获取加密类对象 Cipher cipher =Cipher.getInstance("aes"); SecretKey key =getKey(originKey); //对加密类对象进行初始化 //mode:加密/解密 //key:对原始秘钥处理之后的秘钥 cipher.init(Cipher.ENCRYPT_MODE,key); //使用加密工具类对象对明文进行加密 变成密文 byte[] doFinal= cipher.doFinal(clearText.getBytes()); String encodetext =Base64.encode(doFinal); return new String(encodetext); } private static SecretKey getKey(String originKey) { //不够 初始值为0 byte[]buffer =new byte[16]; //获取用户提供的原始密钥字节数组 byte[] originBytes =originKey.getBytes(); for(int i=0;i<8&&i<originBytes.length;i++){ buffer[i]=originBytes[i]; } SecretKeySpec key= new SecretKeySpec(buffer,"aes"); return key; } }