JAVA实现AES加密算法代码.docx

上传人:b****7 文档编号:8947738 上传时间:2023-02-02 格式:DOCX 页数:4 大小:16.39KB
下载 相关 举报
JAVA实现AES加密算法代码.docx_第1页
第1页 / 共4页
JAVA实现AES加密算法代码.docx_第2页
第2页 / 共4页
JAVA实现AES加密算法代码.docx_第3页
第3页 / 共4页
JAVA实现AES加密算法代码.docx_第4页
第4页 / 共4页
亲,该文档总共4页,全部预览完了,如果喜欢就下载吧!
下载资源
资源描述

JAVA实现AES加密算法代码.docx

《JAVA实现AES加密算法代码.docx》由会员分享,可在线阅读,更多相关《JAVA实现AES加密算法代码.docx(4页珍藏版)》请在冰豆网上搜索。

JAVA实现AES加密算法代码.docx

JAVA实现AES加密算法代码

JAVA实现AES加密算法代码

近些年DES使用越来越少,原因就在于其使用56位密钥,比较容易被破解,近些年来逐渐被AES替代,AES已经变成目前对称加密中最流行算法之一;AES可以使用128、192、和256位密钥,并且用128位分组加密和解密数据。

本文就简单介绍如何通过JAVA实现AES加密。

  1.JAVA实现  闲话少许,掠过AES加密原理及算法,关于这些直接搜索专业网站吧,我们直接看JAVA的具体实现。

  1.1加密  代码有详细解释,不多废话。

  /**  *加密  *  *@paramcontent需要加密的内容  *@parampassword加密密码  *@return  */  publicstaticbyte[]encrypt(Stringcontent,Stringpassword){  try{  KeyGeneratorkgen=KeyGenerator.getInstance("AES");  kgen.init(128,newSecureRandom(password.getBytes()));  SecretKeysecretKey=kgen.generateKey();  byte[]enCodeFormat=secretKey.getEncoded();  SecretKeySpeckey=newSecretKeySpec(enCodeFormat,"AES");  Ciphercipher=Cipher.getInstance("AES");//创建密码器  byte[]byteContent=content.getBytes("utf-8");  cipher.init(Cipher.ENCRYPT_MODE,key);//初始化  byte[]result=cipher.doFinal(byteContent);  returnresult;//加密  }catch(NoSuchAlgorithmExceptione){  e.printStackTrace();  }catch(NoSuchPaddingExceptione){  e.printStackTrace();  }catch(InvalidKeyExceptione){  e.printStackTrace();  }catch(UnsupportedEncodingExceptione){  e.printStackTrace();  }catch(IllegalBlockSizeExceptione){  e.printStackTrace();  }catch(BadPaddingExceptione){  e.printStackTrace();  }  returnnull;  }  /**  *加密  *  *@paramcontent需要加密的内容  *@parampassword加密密码  *@return  */  publicstaticbyte[]encrypt(Stringcontent,Stringpassword){  try{  KeyGeneratorkgen=KeyGenerator.getInstance("AES");  kgen.init(128,newSecureRandom(password.getBytes()));  SecretKeysecretKey=kgen.generateKey();  byte[]enCodeFormat=secretKey.getEncoded();  SecretKeySpeckey=newSecretKeySpec(enCodeFormat,"AES");  Ciphercipher=Cipher.getInstance("AES");//创建密码器  byte[]byteContent=content.getBytes("utf-8");  cipher.init(Cipher.ENCRYPT_MODE,key);//初始化  byte[]result=cipher.doFinal(byteContent);  returnresult;//加密  }catch(NoSuchAlgorithmExceptione){  e.printStackTrace();  }catch(NoSuchPaddingExceptione){  e.printStackTrace();  }catch(InvalidKeyExceptione){  e.printStackTrace();  }catch(UnsupportedEncodingExceptione){  e.printStackTrace();  }catch(IllegalBlockSizeExceptione){  e.printStackTrace();  }catch(BadPaddingExceptione){  e.printStackTrace();  }  returnnull;  }  2.2解密  代码有详细注释,不多废话  注意:

解密的时候要传入byte数组  viewplaincopytoclipboardprint?

  /**解密  *@paramcontent待解密内容  *@parampassword解密密钥  *@return  */  publicstaticbyte[]decrypt(byte[]content,Stringpassword){  try{  KeyGeneratorkgen=KeyGenerator.getInstance("AES");  kgen.init(128,newSecureRandom(password.getBytes()));  SecretKeysecretKey=kgen.generateKey();  byte[]enCodeFormat=secretKey.getEncoded();  SecretKeySpeckey=newSecretKeySpec(enCodeFormat,"AES");  Ciphercipher=Cipher.getInstance("AES");//创建密码器  cipher.init(Cipher.DECRYPT_MODE,key);//初始化  byte[]result=cipher.doFinal(content);  returnresult;//加密  }catch(NoSuchAlgorithmExceptione){  e.printStackTrace();  }catch(NoSuchPaddingExceptione){  e.printStackTrace();  }catch(InvalidKeyExceptione){  e.printStackTrace();  }catch(IllegalBlockSizeExceptione){  e.printStackTrace();  }catch(BadPaddingExceptione){  e.printStackTrace();  }  returnnull;  }  /**解密  *@paramcontent待解密内容  *@parampassword解密密钥  *@return  */  publicstaticbyte[]decrypt(byte[]content,Stringpassword){  try{  KeyGeneratorkgen=KeyGenerator.getInstance("AES");  kgen.init(128,newSecureRandom(password.getBytes()));  SecretKeysecretKey=kgen.generateKey();  byte[]enCodeFormat=secretKey.getEncoded();  SecretKeySpeckey=newSecretKeySpec(enCodeFormat,"AES");  Ciphercipher=Cipher.getInstance("AES");//创建密码器  cipher.init(Cipher.DECRYPT_MODE,key);//初始化  byte[]result=cipher.doFinal(content);  returnresult;//加密  }catch(NoSuchAlgorithmExceptione){  e.printStackTrace();  }catch(NoSuchPaddingExceptione){  e.printStackTrace();  }catch(InvalidKeyExceptione){  e.printStackTrace();  }catch(IllegalBlockSizeExceptione){  e.printStackTrace();  }catch(BadPaddingExceptione){  e.printStackTrace();  }  returnnull;  }

2.3测试代码  Stringcontent="test";  Stringpassword="12345678";  //加密  System.out.println("加密前:

"+content);  byte[]encryptResult=encrypt(content,password);  //解密  byte[]decryptResult=decrypt(encryptResult,password);  System.out.println("解密后:

"+newString(decryptResult));  Stringcontent="test";  Stringpassword="12345678";  //加密  System.out.println("加密前:

"+content);  byte[]encryptResult=encrypt(content,password);  //解密  byte[]decryptResult=decrypt(encryptResult,password);  System.out.println("解密后:

"+newString(decryptResult));  输出结果如下:

  加密前:

test  解密后:

test  2.4容易出错的地方  但是如果我们将测试代码修改一下,如下:

  Stringcontent="test";  Stringpassword="12345678";  //加密  System.out.println("加密前:

"+content);  byte[]encryptResult=encrypt(content,password);  try{  StringencryptResultStr=newString(encryptResult,"utf-8");  //解密  byte[]decryptResult=decrypt(encryptResultStr.getBytes("utf-8"),password);  System.out.println("解密后:

"+newString(decryptResult));  }catch(UnsupportedEncodingExceptione){  e.printStackTrace();  }  Stringcontent="test";  Stringpassword="12345678";  //加密  System.out.println("加密前:

"+content);  byte[]encryptResult=encrypt(content,password);  try{  StringencryptResultStr=newString(encryptResult,"utf-8");  //解密  byte[]decryptResult=decrypt(encryptResultStr.getBytes("utf-8"),password);  System.out.println("解密后:

"+newString(decryptResult));  }catch(UnsupportedEncodingExceptione){  e.printStackTrace();  }  则,系统会报出如下异常:

  javax.crypto.IllegalBlockSizeException:

Inputlengthmustbemultipleof16whendecryptingwithpaddedcipher  atcom.sun.crypto.provider.SunJCE_f.b(DashoA13*..)  atcom.sun.crypto.provider.SunJCE_f.b(DashoA13*..)  atcom.sun.crypto.provider.AESCipher.engineDoFinal(DashoA13*..)  atjavax.crypto.Cipher.doFinal(DashoA13*..)  这主要是因为加密后的byte数组是不能强制转换成字符串的,换言之:

字符串和byte数组在这种情况下不是互逆的;要避免这种情况,我们需要做一些修订,可以考虑将二进制数据转换成十六进制表示,主要有如下两个方法:

  2.4.1将二进制转换成16进制  /**将二进制转换成16进制  *@parambuf  *@return  */  publicstaticStringparseByte2HexStr(bytebuf[]){  StringBuffersb=newStringBuffer();  for(inti=0;i  Stringhex=Integer.toHexString(buf[i]&0xFF);  if(hex.length()==1){  hex='0'+hex;  }  sb.append(hex.toUpperCase());  }  returnsb.toString();  }  /**将二进制转换成16进制  *@parambuf  *@return  */  publicstaticStringparseByte2HexStr(bytebuf[]){  StringBuffersb=newStringBuffer();  for(inti=0;i  Stringhex=Integer.toHexString(buf[i]&0xFF);  if(hex.length()==1){  hex='0'+hex;  }  sb.append(hex.toUpperCase());  }  returnsb.toString();  }  2.4.2将16进制转换为二进制  /**将16进制转换为二进制  *@paramhexStr  *@return  */  publicstaticbyte[]parseHexStr2Byte(StringhexStr){  if(hexStr.length()  returnnull;  byte[]result=newbyte[hexStr.length()/2];  for(inti=0;i  inthigh=Integer.parseInt(hexStr.substring(i*2,i*2+1),16);  intlow=Integer.parseInt(hexStr.substring(i*2+1,i*2+2),16);  result[i]=(byte)(high*16+low);  }  returnresult;  }

/**将16进制转换为二进制  *@paramhexStr  *@return  */  publicstaticbyte[]parseHexStr2Byte(StringhexStr){  if(hexStr.length()  returnnull;  byte[]result=newbyte[hexStr.length()/2];  for(inti=0;i  inthigh=Integer.parseInt(hexStr.substring(i*2,i*2+1),16);  intlow=Integer.parseInt(hexStr.substring(i*2+1,i*2+2),16);  result[i]=(byte)(high*16+low);  }  returnresult;  }  然后,我们再修订以上测试代码,如下:

  Stringcontent="test";  Stringpassword="12345678";  //加密  System.out.println("加密前:

"+content);  byte[]encryptResult=encrypt(content,password);  StringencryptResultStr=parseByte2HexStr(encryptResult);  System.out.println("加密后:

"+encryptResultStr);  //解密  byte[]decryptFrom=parseHexStr2Byte(encryptResultStr);  byte[]decryptResult=decrypt(decryptFrom,password);  System.out.println("解密后:

"+newString(decryptResult));  Stringcontent="test";  Stringpassword="12345678";  //加密  System.out.println("加密前:

"+content);  byte[]encryptResult=encrypt(content,password);  StringencryptResultStr=parseByte2HexStr(encryptResult);  System.out.println("加密后:

"+encryptResultStr);  //解密  byte[]decryptFrom=parseHexStr2Byte(encryptResultStr);  byte[]decryptResult=decrypt(decryptFrom,password);  System.out.println("解密后:

"+newString(decryptResult));  测试结果如下:

  加密前:

test  加密后:

73C58BAFE578C59366D8C995CD0B9D6D  解密后:

test  2.5另外一种加密方式  还有一种加密方式,大家可以参考如下:

  /**  *加密  *  *@paramcontent需要加密的内容  *@parampassword加密密码  *@return  */  publicstaticbyte[]encrypt2(Stringcontent,Stringpassword){  try{  SecretKeySpeckey=newSecretKeySpec(password.getBytes(),"AES");  Ciphercipher=Cipher.getInstance("AES/ECB/NoPadding");  byte[]byteContent=content.getBytes("utf-8");  cipher.init(Cipher.ENCRYPT_MODE,key);//初始化  byte[]result=cipher.doFinal(byteContent);  returnresult;//加密  }catch(NoSuchAlgorithmExceptione){  e.printStackTrace();  }catch(NoSuchPaddingExceptione){  e.printStackTrace();  }catch(InvalidKeyExceptione){  e.printStackTrace();  }catch(UnsupportedEncodingExceptione){  e.printStackTrace();  }catch(IllegalBlockSizeExceptione){  e.printStackTrace();  }catch(BadPaddingExceptione){  e.printStackTrace();  }  returnnull;  }  /**  *加密  *  *@paramcontent需要加密的内容  *@parampassword加密密码  *@return  */  publicstaticbyte[]encrypt2(Stringcontent,Stringpassword){  try{  SecretKeySpeckey=newSecretKeySpec(password.getBytes(),"AES");  Ciphercipher=Cipher.getInstance("AES/ECB/NoPadding");  byte[]byteContent=content.getBytes("utf-8");  cipher.init(Cipher.ENCRYPT_MODE,key);//初始化  byte[]result=cipher.doFinal(byteContent);  returnresult;//加密  }catch(NoSuchAlgorithmExceptione){  e.printStackTrace();  }catch(NoSuchPaddingExceptione){  e.printStackTrace();  }catch(InvalidKeyExceptione){  e.printStackTrace();  }catch(UnsupportedEncodingExceptione){  e.print

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 初中教育 > 数学

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1