熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

AES對稱加密例子

2022-06-13   來源: Java核心技術 

   什麼是AES

  AES是一種對稱的私鑰加密技術它支持位加密

   AES和Java

  從jse開始集成了JCE包

  現在的java支持位key的加密(下面的程序也是以位為例講解的)

   如何使用JCE

  例

  Java代碼

  import javasecurity*;

  import javaxcrypto*;

  import javaxcryptospec*;

  import javaio*;

  /**

  * 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(buflength * );

  int i;

  for (i = ; i < buflength; i++) {

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

  strbufappend();

  strbufappend(LongtoString((int) buf[i] & xff ));

  }

  return strbuftoString();

  }

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

  String message=This is just an example;

  // Get the KeyGenerator

  KeyGenerator kgen = KeyGeneratorgetInstance(AES);

  kgeninit(); // and bits may not be available

  // Generate the secret key specs

  SecretKey skey = kgengenerateKey();

  byte[] raw = skeygetEncoded();

  SecretKeySpec skeySpec = new SecretKeySpec(raw AES);

  // Instantiate the cipher

  Cipher cipher = CiphergetInstance(AES);

  cipherinit(CipherENCRYPT_MODE skeySpec);

  byte[] encrypted =

  cipherdoFinal((argslength == ?

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

  Systemoutprintln(encrypted string: + asHex(encrypted));

  cipherinit(CipherDECRYPT_MODE skeySpec);

  byte[] original =

  cipherdoFinal(encrypted);

  String originalString = new String(original);

  Systemoutprintln(Original string: +

  originalString + + asHex(original));

  }

  }

  import javasecurity*;

  import javaxcrypto*;

  import javaxcryptospec*;

  import javaio*;

  /**

  * 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(buflength * );

  int i;

  for (i = ; i < buflength; i++) {

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

  strbufappend();

  strbufappend(LongtoString((int) buf[i] & xff ));

  }

  return strbuftoString();

  }

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

  String message=This is just an example;

  // Get the KeyGenerator

  KeyGenerator kgen = KeyGeneratorgetInstance(AES);

  kgeninit(); // and bits may not be available

  // Generate the secret key specs

  SecretKey skey = kgengenerateKey();

  byte[] raw = skeygetEncoded();

  SecretKeySpec skeySpec = new SecretKeySpec(raw AES);

  // Instantiate the cipher

  Cipher cipher = CiphergetInstance(AES);

  cipherinit(CipherENCRYPT_MODE skeySpec);

  byte[] encrypted =

  cipherdoFinal((argslength == ?

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

  Systemoutprintln(encrypted string: + asHex(encrypted));

  cipherinit(CipherDECRYPT_MODE skeySpec);

  byte[] original =

  cipherdoFinal(encrypted);

  String originalString = new String(original);

  Systemoutprintln(Original string: +

  originalString + + asHex(original));

  }

  }

   更強壯的加密

  kgeninit(); // and bits also available

  按照原文提示的地址可以更新下一個包然後稍微修改下加密位數就可以了不過jdk默認只支持位的加密實際上作者也建議同時利用SSL比單獨一味強調加密位數效果要好

   同時使用SSL和AES

  server端

  Java代碼

  import javaio*;

  import javasecurity*;

  import ssl*;

  import javautilregex*;

  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)

  SSLServerSocketFactorygetDefault();

  s =(SSLServerSocket)sslSrvFactcreateServerSocket();

  SSLSocket in = (SSLSocket)saccept();

  String str[]=ingetSupportedCipherSuites();

  int len = strlength;

  String set[] = new String[len];

  int j= k = len;

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

  // Determine if pattern exists in input

  matcher = patternmatcher(str[i]);

  matchFound = matcherfind();

  if (matchFound)

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

  else

  set[k] = str[i];

  }

  insetEnabledCipherSuites(set);

  str=ingetEnabledCipherSuites();

  Systemoutprintln(Available Suites after Set:);

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

  Systemoutprintln(str[i]);

  Systemoutprintln(Using cipher suite: +

  (ingetSession())getCipherSuite());

  PrintWriter out = new PrintWriter (ingetOutputStream()

  true);

  outprintln(Hello on a SSL socket);

  inclose();

  } catch (Exception e) {

  Systemoutprintln(Exception + e);

  }

  }

  }

  import javaio*;

  import javasecurity*;

  import ssl*;

  import javautilregex*;

  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)

  SSLServerSocketFactorygetDefault();

  s =(SSLServerSocket)sslSrvFactcreateServerSocket();

  SSLSocket in = (SSLSocket)saccept();

  String str[]=ingetSupportedCipherSuites();

  int len = strlength;

  String set[] = new String[len];

  int j= k = len;

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

  // Determine if pattern exists in input

  matcher = patternmatcher(str[i]);

  matchFound = matcherfind();

  if (matchFound)

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

  else

  set[k] = str[i];

  }

  insetEnabledCipherSuites(set);

  str=ingetEnabledCipherSuites();

  Systemoutprintln(Available Suites after Set:);

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

  Systemoutprintln(str[i]);

  Systemoutprintln(Using cipher suite: +

  (ingetSession())getCipherSuite());

  PrintWriter out = new PrintWriter (ingetOutputStream()

  true);

  outprintln(Hello on a SSL socket);

  inclose();

  } catch (Exception e) {

  Systemoutprintln(Exception + e);

  }

  }

  }

  client端

  Java代碼

  import javaio*;

  import javasecurity*;

  import ssl*;

  import javautilregex*;

  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)SSLSocketFactorygetDefault();

  SSLSocket s =

  (SSLSocket)sslFactcreateSocket(argslength == ?

   : args[] );

  String str[]=sgetSupportedCipherSuites();

  int len = strlength;

  String set[] = new String[len];

  int j= k = len;

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

  Systemoutprintln(str[i]);

  // Determine if pattern exists in input

  matcher = patternmatcher(str[i]);

  matchFound = matcherfind();

  if (matchFound)

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

  else

  set[k] = str[i];

  }

  ssetEnabledCipherSuites(set);

  str=sgetEnabledCipherSuites();

  Systemoutprintln(Available Suites after Set:);

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

  Systemoutprintln(str[i]);

  OutputStream out = sgetOutputStream();

  BufferedReader in = new BufferedReader (

  new InputStreamReader(sgetInputStream()));

  String mesg = inreadLine();

  Systemoutprintln(Socket message: + mesg);

  inclose();

  } catch (Exception e) {

  Systemoutprintln(Exception + e);

  }

  }

  }

  import javaio*;

  import javasecurity*;

  import ssl*;

  import javautilregex*;

  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)SSLSocketFactorygetDefault();

  SSLSocket s =

  (SSLSocket)sslFactcreateSocket(argslength == ?

   : args[] );

  String str[]=sgetSupportedCipherSuites();

  int len = strlength;

  String set[] = new String[len];

  int j= k = len;

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

  Systemoutprintln(str[i]);

  // Determine if pattern exists in input

  matcher = patternmatcher(str[i]);

  matchFound = matcherfind();

  if (matchFound)

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

  else

  set[k] = str[i];

  }

  ssetEnabledCipherSuites(set);

  str=sgetEnabledCipherSuites();

  Systemoutprintln(Available Suites after Set:);

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

  Systemoutprintln(str[i]);

  OutputStream out = sgetOutputStream();

  BufferedReader in = new BufferedReader (

  new InputStreamReader(sgetInputStream()));

  String mesg = inreadLine();

  Systemoutprintln(Socket message: + mesg);

  inclose();

  } catch (Exception e) {

  Systemoutprintln(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__MDSSL_DH_anon_WITH_DES_CBC_SHASSL_DH_anon_WITH_DES_EDE_CBC_SHATLS_DH_anon_WITH_AES__CBC_SHASSL_DH_anon_WITH_RC__MDSSL_RSA_WITH_NULL_SHASSL_RSA_WITH_NULL_MDSSL_DHE_DSS_EXPORT_WITH_DES_CBC_SHASSL_DHE_RSA_EXPORT_WITH_DES_CBC_SHASSL_RSA_EXPORT_WITH_DES_CBC_SHASSL_RSA_EXPORT_WITH_RC__MDSSL_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__MDUsing cipher suite: TLS_RSA_WITH_AES__CBC_SHA

  別人的例子

  Java代碼

  /**

  *PrivateExmaplejava

  *Copyright

  */

  import javaxcryptoCipher;

  import javaxcryptoKeyGenerator;

  import javasecurityKey;

  /**

  *&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

  Systemoutprintln(\nStart generate AES key);

  KeyGenerator keyGen=KeyGeneratorgetInstance(AES);

  keyGeninit();

  Key key=keyGengenerateKey();

  Systemoutprintln(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;PKCSPadding&Ecirc;&Ccedil;&Igrave;&amp;&sup;&amp;·&frac;·‥

  Cipher cipher=CiphergetInstance(AES/ECB/PKCSPadding);

  Systemoutprintln(\n+ciphergetProvider()getInfo());

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

  Systemoutprintln(\nStart encryption:);

  cipherinit(CipherENCRYPT_MODEkey);

  byte[] cipherText=cipherdoFinal(plainText);

  Systemoutprintln(Finish encryption:);

  Systemoutprintln(new String(cipherTextUTF));

  Systemoutprintln(\nStart decryption:);

  cipherinit(CipherDECRYPT_MODEkey);

  byte[] newPlainText=cipherdoFinal(cipherText);

  Systemoutprintln(Finish decryption:);

  Systemoutprintln(new String(newPlainTextUTF));

  }

  }

  /**

  *PrivateExmaplejava

  *Copyright

  */

  import javaxcryptoCipher;

  import javaxcryptoKeyGenerator;

  import javasecurityKey;

  /**

  *&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

  Systemoutprintln(\nStart generate AES key);

  KeyGenerator keyGen=KeyGeneratorgetInstance(AES);

  keyGeninit();

  Key key=keyGengenerateKey();

  Systemoutprintln(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;PKCSPadding&Ecirc;&Ccedil;&Igrave;&amp;&sup;&amp;·&frac;·‥

  Cipher cipher=CiphergetInstance(AES/ECB/PKCSPadding);

  Systemoutprintln(\n+ciphergetProvider()getInfo());

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

  Systemoutprintln(\nStart encryption:);

  cipherinit(CipherENCRYPT_MODEkey);

  byte[] cipherText=cipherdoFinal(plainText);

  Systemoutprintln(Finish encryption:);

  Systemoutprintln(new String(cipherTextUTF));

  Systemoutprintln(\nStart decryption:);

  cipherinit(CipherDECRYPT_MODEkey);

  byte[] newPlainText=cipherdoFinal(cipherText);

  Systemoutprintln(Finish decryption:);

  Systemoutprintln(new String(newPlainTextUTF));

  }

  }

  自己稍加修改的例子

  Java代碼

  byte[] plainText=getBytes();

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

  Systemoutprintln(\nStart generate AES key);

  KeyGenerator keyGen=KeyGeneratorgetInstance(AES);

  String pwd = passord;

  keyGeninit( new SecureRandom(pwdgetBytes()));

  //keyGeninit();

  //Key key=keyGengenerateKey();

  SecretKey skey = keyGengenerateKey();

  byte[] raw = skeygetEncoded();

  SecretKeySpec skeySpec = new SecretKeySpec(raw AES);

  Systemoutprintln(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;PKCSPadding&Ecirc;&Ccedil;&Igrave;&amp;&sup;&amp;?E&frac;?E‥

  Cipher cipher=CiphergetInstance(AES);

  Systemoutprintln(\n+ciphergetProvider()getInfo());

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

  Systemoutprintln(\nStart encryption:);

  cipherinit(CipherENCRYPT_MODEskeySpec);

  byte[] cipherText=cipherdoFinal(plainText);

  Systemoutprintln(Finish encryption:);

  Systemoutprintln(new String(cipherTextUTF));

  Systemoutprintln(\nStart decryption:);

  cipherinit(CipherDECRYPT_MODEskeySpec);

  byte[] newPlainText=cipherdoFinal(cipherText);

  Systemoutprintln(Finish decryption:);

  Systemoutprintln(new String(newPlainTextUTF));

  }


From:http://tw.wingwit.com/Article/program/Java/hx/201311/25576.html
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.