知识大全 AES对称加密例子

Posted

篇首语:五陵年少金市东,银鞍白马渡春风。本文由小常识网(cha138.com)小编为大家整理,主要介绍了知识大全 AES对称加密例子相关的知识,希望对你有一定的参考价值。

AES对称加密例子  以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧!

   什么是AES

  AES是一种对称的私钥加密技术 它支持 位加密

   AES和Java

  从j se 开始 集成了JCE包

  现在的java支持 位key的加密 (下面的程序也是以 位为例讲解的)

   如何使用JCE

  例

  Java代码

  import java security *;

  import javax crypto *;

  import javax crypto spec *;

  import java io *;

  /**

  * This program generates a AES key retrieves its raw bytes and

  * then reinstantiates a AES key from the key bytes

  * The reinstantiated key is used to initialize a AES cipher for

  * encryption and decryption

  */

  public class AES

  /**

  * Turns array of bytes into string

  *

  * @param buf  Array of bytes to convert to hex string

  * @return Generated hex string

  */

  public static String asHex (byte buf[])

  StringBuffer strbuf = new StringBuffer(buf length * );

  int i;

  for (i = ; i < buf length; i++)

  if (((int) buf[i] & xff) < x )

  strbuf append( );

  strbuf append(Long toString((int) buf[i] & xff ));

  

  return strbuf toString();

  

  public static void main(String[] args) throws Exception

  String message= This is just an example ;

  // Get the KeyGenerator

  KeyGenerator kgen = KeyGenerator getInstance( AES );

  kgen init( ); // and bits may not be available

  // Generate the secret key specs

  SecretKey skey = kgen generateKey();

  byte[] raw = skey getEncoded();

  SecretKeySpec skeySpec = new SecretKeySpec(raw AES );

  // Instantiate the cipher

  Cipher cipher = Cipher getInstance( AES );

  cipher init(Cipher ENCRYPT_MODE skeySpec);

  byte[] encrypted =

  cipher doFinal((args length == ?

   This is just an example : args[ ]) getBytes());

  System out println( encrypted string: + asHex(encrypted));

  cipher init(Cipher DECRYPT_MODE skeySpec);

  byte[] original =

  cipher doFinal(encrypted);

  String originalString = new String(original);

  System out println( Original string: +

  originalString + + asHex(original));

  

  

  import java security *;

  import javax crypto *;

  import javax crypto spec *;

  import java io *;

  /**

  * This program generates a AES key retrieves its raw bytes and

  * then reinstantiates a AES key from the key bytes

  * The reinstantiated key is used to initialize a AES cipher for

  * encryption and decryption

  */

  public class AES

  /**

  * Turns array of bytes into string

  *

  * @param bufArray of bytes to convert to hex string

  * @returnGenerated hex string

  */

  public static String asHex (byte buf[])

  StringBuffer strbuf = new StringBuffer(buf length * );

  int i;

  for (i = ; i < buf length; i++)

  if (((int) buf[i] & xff) < x )

  strbuf append( );

  strbuf append(Long toString((int) buf[i] & xff ));

  

  return strbuf toString();

  

  public static void main(String[] args) throws Exception

  String message= This is just an example ;

  // Get the KeyGenerator

  KeyGenerator kgen = KeyGenerator getInstance( AES );

  kgen init( ); // and bits may not be available

  // Generate the secret key specs

  SecretKey skey = kgen generateKey();

  byte[] raw = skey getEncoded();

  SecretKeySpec skeySpec = new SecretKeySpec(raw AES );

  // Instantiate the cipher

  Cipher cipher = Cipher getInstance( AES );

  cipher init(Cipher ENCRYPT_MODE skeySpec);

  byte[] encrypted =

  cipher doFinal((args length == ?

   This is just an example : args[ ]) getBytes());

  System out println( encrypted string: + asHex(encrypted));

  cipher init(Cipher DECRYPT_MODE skeySpec);

  byte[] original =

  cipher doFinal(encrypted);

  String originalString = new String(original);

  System out println( Original string: +

  originalString + + asHex(original));

  

  

   更强壮的加密

  kgen init( ); // and bits also available

  按照原文提示的地址可以更新下一个包 然后稍微修改下加密位数就可以了 不过jdk 默认只支持 位的加密 实际上 作者也建议同时利用SSL 比单独一味强调加密位数效果要好

   同时使用SSL和AES

  server端

  Java代码

  import java io *;

  import java security *;

  import ssl *;

  import java util regex *;

  public class HelloServerSSL

  public static void main(String[] args)

  SSLServerSocket s;

  // Pick all AES algorithms of bits key size

  String patternString = AES * ;

  Pattern pattern = pile(patternString);

  Matcher matcher;

  boolean matchFound;

  try

  SSLServerSocketFactory sslSrvFact =

  (SSLServerSocketFactory)

  SSLServerSocketFactory getDefault();

  s =(SSLServerSocket)sslSrvFact createServerSocket( );

  SSLSocket in = (SSLSocket)s accept();

  String str[]=in getSupportedCipherSuites();

  int len = str length;

  String set[] = new String[len];

  int j= k = len ;

  for (int i= ; i < len; i++)

  // Determine if pattern exists in input

  matcher = pattern matcher(str[i]);

  matchFound = matcher find();

  if (matchFound)

  set[j++] = str[i];

  else

  set[k ] = str[i];

  

  in setEnabledCipherSuites(set);

  str=in getEnabledCipherSuites();

  System out println( Available Suites after Set: );

  for (int i= ; i < str length; i++)

  System out println(str[i]);

  System out println( Using cipher suite: +

  (in getSession()) getCipherSuite());

  PrintWriter out = new PrintWriter (in getOutputStream()

  true);

  out println( Hello on a SSL socket );

  in close();

   catch (Exception e)

  System out println( Exception + e);

  

  

  

  import java io *;

  import java security *;

  import ssl *;

  import java util regex *;

  public class HelloServerSSL

  public static void main(String[] args)

  SSLServerSocket s;

  // Pick all AES algorithms of bits key size

  String patternString = AES * ;

  Pattern pattern = pile(patternString);

  Matcher matcher;

  boolean matchFound;

  try

  SSLServerSocketFactory sslSrvFact =

  (SSLServerSocketFactory)

  SSLServerSocketFactory getDefault();

  s =(SSLServerSocket)sslSrvFact createServerSocket( );

  SSLSocket in = (SSLSocket)s accept();

  String str[]=in getSupportedCipherSuites();

  int len = str length;

  String set[] = new String[len];

  int j= k = len ;

  for (int i= ; i < len; i++)

  // Determine if pattern exists in input

  matcher = pattern matcher(str[i]);

  matchFound = matcher find();

  if (matchFound)

  set[j++] = str[i];

  else

  set[k ] = str[i];

  

  in setEnabledCipherSuites(set);

  str=in getEnabledCipherSuites();

  System out println( Available Suites after Set: );

  for (int i= ; i < str length; i++)

  System out println(str[i]);

  System out println( Using cipher suite: +

  (in getSession()) getCipherSuite());

  PrintWriter out = new PrintWriter (in getOutputStream()

  true);

  out println( Hello on a SSL socket );

  in close();

   catch (Exception e)

  System out println( Exception + e);

  

  

  

  client端

  Java代码

  import java io *;

  import java security *;

  import ssl *;

  import java util regex *;

  public class HelloClientSSL

  public static void main(String[] args)

  // Pick all AES algorithms of bits key size

  String patternString = AES * ;

  Pattern pattern = pile(patternString);

  Matcher matcher;

  boolean matchFound;

  try

  SSLSocketFactory sslFact =

  (SSLSocketFactory)SSLSocketFactory getDefault();

  SSLSocket s =

  (SSLSocket)sslFact createSocket(args length == ?

   : args[ ] );

  String str[]=s getSupportedCipherSuites();

  int len = str length;

  String set[] = new String[len];

  int j= k = len ;

  for (int i= ; i < len; i++)

  System out println(str[i]);

  // Determine if pattern exists in input

  matcher = pattern matcher(str[i]);

  matchFound = matcher find();

  if (matchFound)

  set[j++] = str[i];

  else

  set[k ] = str[i];

  

  s setEnabledCipherSuites(set);

  str=s getEnabledCipherSuites();

  System out println( Available Suites after Set: );

  for (int i= ; i < str length; i++)

  System out println(str[i]);

  OutputStream out = s getOutputStream();

  BufferedReader in = new BufferedReader (

  new InputStreamReader(s getInputStream()));

  String mesg = in readLine();

  System out println( Socket message: + mesg);

  in close();

   catch (Exception e)

  System out println( Exception + e);

  

  

  

  import java io *;

  import java security *;

  import ssl *;

  import java util regex *;

  public class HelloClientSSL

  public static void main(String[] args)

  // Pick all AES algorithms of bits key size

  String patternString = AES * ;

  Pattern pattern = pile(patternString);

  Matcher matcher;

  boolean matchFound;

  try

  SSLSocketFactory sslFact =

  (SSLSocketFactory)SSLSocketFactory getDefault();

  SSLSocket s =

  (SSLSocket)sslFact createSocket(args length == ?

   : args[ ] );

  String str[]=s getSupportedCipherSuites();

  int len = str length;

  String set[] = new String[len];

  int j= k = len ;

  for (int i= ; i < len; i++)

  System out println(str[i]);

  // Determine if pattern exists in input

  matcher = pattern matcher(str[i]);

  matchFound = matcher find();

  if (matchFound)

  set[j++] = str[i];

  else

  set[k ] = str[i];

  

  s setEnabledCipherSuites(set);

  str=s getEnabledCipherSuites();

  System out println( Available Suites after Set: );

  for (int i= ; i < str length; i++)

  System out println(str[i]);

  OutputStream out = s getOutputStream();

  BufferedReader in = new BufferedReader (

  new InputStreamReader(s getInputStream()));

  String mesg = in readLine();

  System out println( Socket message: + mesg);

  in close();

   catch (Exception e)

  System out println( Exception + e);

  

  

  

  运行结果

  Available Suites after Set:TLS_RSA_WITH_AES_ _CBC_SHATLS_DHE_RSA_WITH_AES_ _CBC_SHATLS_DHE_DSS_WITH_AES_ _CBC_SHATLS_DH_anon_WITH_AES_ _CBC_SHASSL_DH_anon_EXPORT_WITH_DES _CBC_SHASSL_DH_anon_EXPORT_WITH_RC _ _MD SSL_DH_anon_WITH_DES_CBC_SHASSL_DH_anon_WITH_ DES_EDE_CBC_SHATLS_DH_anon_WITH_AES_ _CBC_SHASSL_DH_anon_WITH_RC _ _MD SSL_RSA_WITH_NULL_SHASSL_RSA_WITH_NULL_MD SSL_DHE_DSS_EXPORT_WITH_DES _CBC_SHASSL_DHE_RSA_EXPORT_WITH_DES _CBC_SHASSL_RSA_EXPORT_WITH_DES _CBC_SHASSL_RSA_EXPORT_WITH_RC _ _MD SSL_DHE_DSS_WITH_DES_CBC_SHASSL_DHE_RSA_WITH_DES_CBC_SHASSL_RSA_WITH_DES_CBC_SHASSL_DHE_DSS_WITH_ DES_EDE_CBC_SHASSL_DHE_RSA_WITH_ DES_EDE_CBC_SHASSL_RSA_WITH_ DES_EDE_CBC_SHATLS_DHE_DSS_WITH_AES_ _CBC_SHATLS_DHE_RSA_WITH_AES_ _CBC_SHATLS_RSA_WITH_AES_ _CBC_SHASSL_RSA_WITH_RC _ _SHASSL_RSA_WITH_RC _ _MD Using cipher suite: TLS_RSA_WITH_AES_ _CBC_SHA

  别人的例子

  Java代码

  /**

  *PrivateExmaple java

  *Copyright

  */

  import javax crypto Cipher;

  import javax crypto KeyGenerator;

  import java security Key;

  /**

  *&Euml;&frac ;?&frac ;&Oacute;&Atilde;&Uuml;&amp;&amp;±&amp;&Ouml;¤&Iuml;&amp;&Iuml;&amp;&amp;u&Atilde;&Uuml;&ETH;&Ocirc;

  */

  public class PrivateExample

  public static void main(String[] args) throws Exception

  byte[] plainText= getBytes();

  //&Iacute;‥&sup ;&amp;KeyGenerator&ETH;&Icirc;&sup ;&Eacute;&Ograve;&amp;&amp;&amp;key

  System out println( \\nStart generate AES key );

  KeyGenerator keyGen=KeyGenerator getInstance( AES );

  keyGen init( );

  Key key=keyGen generateKey();

  System out println( Finish generating AES key );

  //&amp;&amp;&amp;&Atilde;&Ograve;&amp;&amp;&amp;&Euml;&frac ;?&frac ;&Oacute;&Atilde;&Uuml;&Agrave;aCipher&amp;&amp;ECB&Ecirc;&Ccedil;&frac ;&Oacute;&Atilde;&Uuml;·&frac ;&Ecirc;&frac ;&amp;&amp;PKCS Padding&Ecirc;&Ccedil;&Igrave;&amp;&sup ;&amp;·&frac ;·‥

  Cipher cipher=Cipher getInstance( AES/ECB/PKCS Padding );

  System out println( \\n +cipher getProvider() getInfo());

  //&Ecirc;&sup ;&Oacute;&Atilde;&Euml;&frac ;?&frac ;&Oacute;&Atilde;&Uuml;

  System out println( \\nStart encryption: );

  cipher init(Cipher ENCRYPT_MODE key);

  byte[] cipherText=cipher doFinal(plainText);

  System out println( Finish encryption: );

  System out println(new String(cipherText UTF ));

  System out println( \\nStart decryption: );

  cipher init(Cipher DECRYPT_MODE key);

  byte[] newPlainText=cipher doFinal(cipherText);

  System out println( Finish decryption: );

  System out println(new String(newPlainText UTF ));

  

  

  /**

  *PrivateExmaple java

  *Copyright

  */

  import javax crypto Cipher;

  import javax crypto KeyGenerator;

  import java security Key;

  /**

  *&Euml;&frac ;?&frac ;&Oacute;&Atilde;&Uuml;&amp;&amp;±&amp;&Ouml;¤&Iuml;&amp;&Iuml;&amp;&amp;u&Atilde;&Uuml;&ETH;&Ocirc;

  */

  public class PrivateExample

  public static void main(String[] args) throws Exception

  byte[] plainText= getBytes();

  //&Iacute;‥&sup ;&amp;KeyGenerator&ETH;&Icirc;&sup ;&Eacute;&Ograve;&amp;&amp;&amp;key

  System out println( \\nStart generate AES key );

  KeyGenerator keyGen=KeyGenerator getInstance( AES );

  keyGen init( );

  Key key=keyGen generateKey();

  System out println( Finish generating AES key );

  //&amp;&amp;&amp;&Atilde;&Ograve;&amp;&amp;&amp;&Euml;&frac ;?&frac ;&Oacute;&Atilde;&Uuml;&Agrave;aCipher&amp;&amp;ECB&Ecirc;&Ccedil;&frac ;&Oacute;&Atilde;&Uuml;·&frac ;&Ecirc;&frac ;&amp;&amp;PKCS Padding&Ecirc;&Ccedil;&Igrave;&amp;&sup ;&amp;·&frac ;·‥

  Cipher cipher=Cipher getInstance( AES/ECB/PKCS Padding );

  System out println( \\n +cipher getProvider() getInfo());

  //&Ecirc;&sup ;&Oacute;&Atilde;&Euml;&frac ;?&frac ;&Oacute;&Atilde;&Uuml;

  System out println( \\nStart encryption: );

  cipher init(Cipher ENCRYPT_MODE key);

  byte[] cipherText=cipher doFinal(plainText);

  System out println( Finish encryption: );

  System out println(new String(cipherText UTF ));

  System out println( \\nStart decryption: );

  cipher init(Cipher DECRYPT_MODE key);

  byte[] newPlainText=cipher doFinal(cipherText);

  System out println( Finish decryption: );

  System out println(new String(newPlainText UTF ));

  

  

  自己稍加修改的例子

  Java代码

  byte[] plainText= getBytes();

  //&Iacute;‥&sup ;&amp;KeyGenerator&ETH;&Icirc;&sup ;&Eacute;&Ograve;&amp;&amp;&amp;key

  System out println( \\nStart generate AES key );

  KeyGenerator keyGen=KeyGenerator getInstance( AES );

  String pwd = passord ;

  keyGen init( new SecureRandom(pwd getBytes()));

  //keyGen init( );

  //Key key=keyGen generateKey();

  SecretKey skey = keyGen generateKey();

  byte[] raw = skey getEncoded();

  SecretKeySpec skeySpec = new SecretKeySpec(raw AES );

  System out println( Finish generating AES key );

  //&amp;&amp;&amp;&Atilde;&Ograve;&amp;&amp;&amp;&Euml;&frac ;?&frac ;&Oacute;&Atilde;&Uuml;&Agrave;aCipher&amp;&amp;ECB&Ecirc;&Ccedil;&frac ;&Oacute;&Atilde;&Uuml;?E&frac ;&Ecirc;&frac ;&amp;&amp;PKCS Padding&Ecirc;&Ccedil;&Igrave;&amp;&sup ;&amp;?E&frac ;?E‥

  Cipher cipher=Cipher getInstance( AES );

  System out println( \\n +cipher getProvider() getInfo());

  //&Ecirc;&sup ;&Oacute;&Atilde;&Euml;&frac ;?&frac ;&Oacute;&Atilde;&Uuml;

  System out println( \\nStart encryption: );

  cipher init(Cipher ENCRYPT_MODE skeySpec);

  byte[] cipherText=cipher doFinal(plainText);

  System out println( Finish encryption: );

  System out println(new String(cipherText UTF ));

  System out println( \\nStart decryption: );

  cipher init(Cipher DECRYPT_MODE skeySpec);

  byte[] newPlainText=cipher doFinal(cipherText);

  System out println( Finish decryption: );

  System out println(new String(newPlainText UTF ));

cha138/Article/program/Java/hx/201311/25576

相关参考

知识大全 C#对称加密解密算法

C#对称加密解密算法  以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧!  ///<summary

知识大全 .NET对称加密实践 (新手教程)

.NET对称加密实践(新手教程)  以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧!  在使用NET框架

知识大全 使用DES对称加密代码,支持中文

使用DES对称加密代码,支持中文  以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧!//名称空间usin

知识大全 C# 对称算法,加密解密类

C#对称算法,加密解密类  以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧!  模块编号 &n

知识大全 .NET中的密码学--对称加密

.NET中的密码学--对称加密  以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧!  介绍  在net之

知识大全 java非对称加密的源代码(RSA)

java非对称加密的源代码(RSA)  以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧!  鉴于rsa加

知识大全 Java生成RSA非对称型加密的公钥和私钥

Java生成RSA非对称型加密的公钥和私钥  以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧!  非对称

知识大全 漫谈Java加密技术(二)

漫谈Java加密技术(二)  以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧!  接下来我们介绍对称加密

知识大全 通过 Java 如何实现 AES 密码算法

通过Java如何实现AES密码算法  以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧!  有关AES的一

知识大全 AES算法的JAVA实现

AES算法的JAVA实现  以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧!  packagemyLib