Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1676246
  • 博文数量: 585
  • 博客积分: 14610
  • 博客等级: 上将
  • 技术积分: 7402
  • 用 户 组: 普通用户
  • 注册时间: 2008-05-15 10:52
文章存档

2013年(5)

2012年(214)

2011年(56)

2010年(66)

2009年(44)

2008年(200)

分类: Java

2010-11-24 10:25:43

原文地址http://java.sun.com/developer/technicalArticles/Security/AES/AES_v1.html
2000年9月开始,nist开始支持fips,来取代已经过时的des(Data Enryption Strandard).

1 什么是AES
     AES是一种对称的私钥加密技术。它支持128,192,256位加密。


2 AES和Java
     从j2se1.4.2开始,集成了JCE包。
     现在的java支持128位key的加密。(下面的程序也是以128位为例讲解的)


3 如何使用JCE

Java代码
  1. import java.security.*;  
  2. import javax.crypto.*;  
  3. import javax.crypto.spec.*;  
  4. import java.io.*;  
  5.   
  6. /** 
  7. * This program generates a AES key, retrieves its raw bytes, and 
  8. * then reinstantiates a AES key from the key bytes. 
  9. * The reinstantiated key is used to initialize a AES cipher for 
  10. * encryption and decryption. 
  11. */  
  12.   
  13. public class AES {  
  14.   
  15.   /** 
  16.   * Turns array of bytes into string 
  17.   * 
  18.   * @param buf  Array of bytes to convert to hex string 
  19.   * @return Generated hex string 
  20.   */  
  21.   public static String asHex (byte buf[]) {  
  22.    StringBuffer strbuf = new StringBuffer(buf.length * 2);  
  23.    int i;  
  24.   
  25.    for (i = 0; i < buf.length; i++) {  
  26.     if (((int) buf[i] & 0xff) < 0x10)  
  27.   strbuf.append("0");  
  28.   
  29.     strbuf.append(Long.toString((int) buf[i] & 0xff16));  
  30.    }  
  31.   
  32.    return strbuf.toString();  
  33.   }  
  34.   
  35.   public static void main(String[] args) throws Exception {  
  36.   
  37.     String message="This is just an example";  
  38.   
  39.     // Get the KeyGenerator  
  40.   
  41.     KeyGenerator kgen = KeyGenerator.getInstance("AES");  
  42.     kgen.init(128); // 192 and 256 bits may not be available  
  43.   
  44.   
  45.     // Generate the secret key specs.  
  46.     SecretKey skey = kgen.generateKey();  
  47.     byte[] raw = skey.getEncoded();  
  48.   
  49.     SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");  
  50.   
  51.   
  52.     // Instantiate the cipher  
  53.   
  54.     Cipher cipher = Cipher.getInstance("AES");  
  55.   
  56.     cipher.init(Cipher.ENCRYPT_MODE, skeySpec);  
  57.   
  58.     byte[] encrypted =  
  59.       cipher.doFinal((args.length == 0 ?  
  60.        "This is just an example" : args[0]).getBytes());  
  61.     System.out.println("encrypted string: " + asHex(encrypted));  
  62.   
  63.     cipher.init(Cipher.DECRYPT_MODE, skeySpec);  
  64.     byte[] original =  
  65.       cipher.doFinal(encrypted);  
  66.     String originalString = new String(original);  
  67.     System.out.println("Original string: " +  
  68.       originalString + " " + asHex(original));  
  69.   }  
  70. }  
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 * 2); int i; for (i = 0; i < buf.length; i++) { if (((int) buf[i] & 0xff) < 0x10) strbuf.append("0"); strbuf.append(Long.toString((int) buf[i] & 0xff, 16)); } 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(128); // 192 and 256 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 == 0 ? "This is just an example" : args[0]).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)); } }
4 更强壮的加密
   kgen.init(256); // 128 and 192 bits also available
   按照原文提示的地址可以更新下一个包,然后稍微修改下加密位数就可以了。不过jdk1.4默认只支持128位的加密,实际上,作者也建议同时利用SSL,比单独一味强调加密位数效果要好。
5 同时使用SSL和AES

server端


Java代码
  1. import java.io.*;  
  2. import java.security.*;  
  3. import javax.net.ssl.*;  
  4.   
  5.   
  6. import java.util.regex.*;  
  7.   
  8.   
  9. public class HelloServerSSL {  
  10.   public static void main(String[] args) {  
  11.     SSLServerSocket s;  
  12.   
  13.   
  14.     // Pick all AES algorithms of 256 bits key size  
  15.     String patternString = "AES.*256";  
  16.     Pattern pattern = Pattern.compile(patternString);  
  17.     Matcher matcher;  
  18.     boolean matchFound;  
  19.   
  20.     try {  
  21.       SSLServerSocketFactory sslSrvFact =  
  22.         (SSLServerSocketFactory)  
  23.           SSLServerSocketFactory.getDefault();  
  24.       s =(SSLServerSocket)sslSrvFact.createServerSocket(8181);  
  25.   
  26.       SSLSocket in = (SSLSocket)s.accept();  
  27.   
  28.   
  29.       String str[]=in.getSupportedCipherSuites();  
  30.   
  31.       int len = str.length;  
  32.       String set[] = new String[len];  
  33.   
  34.       int j=0, k = len-1;  
  35.       for (int i=0; i < len; i++) {  
  36.   
  37.         // Determine if pattern exists in input  
  38.         matcher = pattern.matcher(str[i]);  
  39.         matchFound = matcher.find();  
  40.   
  41.         if (matchFound)  
  42.           set[j++] = str[i];  
  43.         else  
  44.           set[k--] = str[i];  
  45.       }  
  46.   
  47.       in.setEnabledCipherSuites(set);  
  48.   
  49.       str=in.getEnabledCipherSuites();  
  50.   
  51.       System.out.println("Available Suites after Set:");  
  52.       for (int i=0; i < str.length; i++)  
  53.         System.out.println(str[i]);  
  54.       System.out.println("Using cipher suite: " +  
  55.          (in.getSession()).getCipherSuite());  
  56.   
  57.       PrintWriter out = new PrintWriter (in.getOutputStream(),  
  58.                         true);  
  59.       out.println("Hello on a SSL socket");  
  60.       in.close();  
  61.     } catch (Exception e) {  
  62.       System.out.println("Exception" + e);  
  63.     }  
  64.   }  
  65. }  
import java.io.*; import java.security.*; import javax.net.ssl.*; import java.util.regex.*; public class HelloServerSSL { public static void main(String[] args) { SSLServerSocket s; // Pick all AES algorithms of 256 bits key size String patternString = "AES.*256"; Pattern pattern = Pattern.compile(patternString); Matcher matcher; boolean matchFound; try { SSLServerSocketFactory sslSrvFact = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); s =(SSLServerSocket)sslSrvFact.createServerSocket(8181); SSLSocket in = (SSLSocket)s.accept(); String str[]=in.getSupportedCipherSuites(); int len = str.length; String set[] = new String[len]; int j=0, k = len-1; for (int i=0; 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=0; 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代码
  1. import java.io.*;  
  2. import java.security.*;  
  3. import javax.net.ssl.*;  
  4.   
  5.   
  6. import java.util.regex.*;  
  7.   
  8.   
  9. public class HelloClientSSL {  
  10.   public static void main(String[] args) {  
  11.   
  12.   
  13.     // Pick all AES algorithms of 256 bits key size  
  14.     String patternString = "AES.*256";  
  15.     Pattern pattern = Pattern.compile(patternString);  
  16.     Matcher matcher;  
  17.     boolean matchFound;  
  18.   
  19.     try {  
  20.   
  21.       SSLSocketFactory sslFact =  
  22.         (SSLSocketFactory)SSLSocketFactory.getDefault();  
  23.       SSLSocket s =  
  24.         (SSLSocket)sslFact.createSocket(args.length == 0 ?  
  25.           "127.0.0.1" : args[0], 8181);  
  26.   
  27.       String str[]=s.getSupportedCipherSuites();  
  28.   
  29.       int len = str.length;  
  30.       String set[] = new String[len];  
  31.   
  32.       int j=0, k = len-1;  
  33.       for (int i=0; i < len; i++) {  
  34.         System.out.println(str[i]);  
  35.   
  36.         // Determine if pattern exists in input  
  37.         matcher = pattern.matcher(str[i]);  
  38.         matchFound = matcher.find();  
  39.   
  40.         if (matchFound)  
  41.           set[j++] = str[i];  
  42.         else  
  43.           set[k--] = str[i];  
  44.       }  
  45.   
  46.       s.setEnabledCipherSuites(set);  
  47.   
  48.       str=s.getEnabledCipherSuites();  
  49.   
  50.       System.out.println("Available Suites after Set:");  
  51.       for (int i=0; i < str.length; i++)  
  52.         System.out.println(str[i]);  
  53.   
  54.       OutputStream out = s.getOutputStream();  
  55.       BufferedReader in = new BufferedReader (  
  56.         new InputStreamReader(s.getInputStream()));  
  57.   
  58.       String mesg = in.readLine();  
  59.       System.out.println("Socket message: " + mesg);  
  60.       in.close();  
  61.     } catch (Exception e) {  
  62.       System.out.println("Exception" + e);  
  63.     }  
  64.   }  
  65. }  
import java.io.*; import java.security.*; import javax.net.ssl.*; import java.util.regex.*; public class HelloClientSSL { public static void main(String[] args) { // Pick all AES algorithms of 256 bits key size String patternString = "AES.*256"; Pattern pattern = Pattern.compile(patternString); Matcher matcher; boolean matchFound; try { SSLSocketFactory sslFact = (SSLSocketFactory)SSLSocketFactory.getDefault(); SSLSocket s = (SSLSocket)sslFact.createSocket(args.length == 0 ? "127.0.0.1" : args[0], 8181); String str[]=s.getSupportedCipherSuites(); int len = str.length; String set[] = new String[len]; int j=0, k = len-1; for (int i=0; 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=0; 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_256_CBC_SHATLS_DHE_RSA_WITH_AES_256_CBC_SHATLS_DHE_DSS_WITH_AES_256_CBC_SHATLS_DH_anon_WITH_AES_256_CBC_SHASSL_DH_anon_EXPORT_WITH_DES40_CBC_SHASSL_DH_anon_EXPORT_WITH_RC4_40_MD5SSL_DH_anon_WITH_DES_CBC_SHASSL_DH_anon_WITH_3DES_EDE_CBC_SHATLS_DH_anon_WITH_AES_128_CBC_SHASSL_DH_anon_WITH_RC4_128_MD5SSL_RSA_WITH_NULL_SHASSL_RSA_WITH_NULL_MD5SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHASSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHASSL_RSA_EXPORT_WITH_DES40_CBC_SHASSL_RSA_EXPORT_WITH_RC4_40_MD5SSL_DHE_DSS_WITH_DES_CBC_SHASSL_DHE_RSA_WITH_DES_CBC_SHASSL_RSA_WITH_DES_CBC_SHASSL_DHE_DSS_WITH_3DES_EDE_CBC_SHASSL_DHE_RSA_WITH_3DES_EDE_CBC_SHASSL_RSA_WITH_3DES_EDE_CBC_SHATLS_DHE_DSS_WITH_AES_128_CBC_SHATLS_DHE_RSA_WITH_AES_128_CBC_SHATLS_RSA_WITH_AES_128_CBC_SHASSL_RSA_WITH_RC4_128_SHASSL_RSA_WITH_RC4_128_MD5Using cipher suite: TLS_RSA_WITH_AES_256_CBC_SHA







别人的例子

Java代码
  1. /** 
  2. *PrivateExmaple.java 
  3. *Copyright 2005-2-16 
  4. */  
  5. import javax.crypto.Cipher;  
  6. import javax.crypto.KeyGenerator;  
  7. import java.security.Key;  
  8.   
  9. /** 
  10. *˽?¼ÓÃÜ&&±&Ö¤Ï&Ï&&uÃÜÐÔ 
  11. */  
  12. public class PrivateExample{  
  13.     public static void main(String[] args) throws Exception{  
  14.       
  15.     byte[] plainText="12345678".getBytes();  
  16.   
  17.     //Í‥¹&KeyGeneratorÐγÉÒ&&&key  
  18.     System.out.println("\nStart generate AES key");  
  19.     KeyGenerator keyGen=KeyGenerator.getInstance("AES");  
  20.     keyGen.init(128);  
  21.     Key key=keyGen.generateKey();  
  22.     System.out.println("Finish generating AES key");  
  23.   
  24.     //&&&ÃÒ&&&˽?¼ÓÃÜÀaCipher&&ECBÊǼÓÃÜ·½Ê½&&PKCS5PaddingÊÇÌ&³&·½·‥  
  25.     Cipher cipher=Cipher.getInstance("AES/ECB/PKCS5Padding");  
  26.     System.out.println("\n"+cipher.getProvider().getInfo());  
  27.   
  28.     //ʹÓÃ˽?¼ÓÃÜ  
  29.     System.out.println("\nStart encryption:");  
  30.     cipher.init(Cipher.ENCRYPT_MODE,key);  
  31.     byte[] cipherText=cipher.doFinal(plainText);  
  32.     System.out.println("Finish encryption:");  
  33.     System.out.println(new String(cipherText,"UTF8"));  
  34.   
  35.     System.out.println("\nStart decryption:");  
  36.     cipher.init(Cipher.DECRYPT_MODE,key);  
  37.     byte[] newPlainText=cipher.doFinal(cipherText);  
  38.     System.out.println("Finish decryption:");  
  39.   
  40.     System.out.println(new String(newPlainText,"UTF8"));  
  41.     }  
  42. }  
/** *PrivateExmaple.java *Copyright 2005-2-16 */ import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import java.security.Key; /** *˽?¼ÓÃÜ&&±&Ö¤Ï&Ï&&uÃÜÐÔ */ public class PrivateExample{ public static void main(String[] args) throws Exception{ byte[] plainText="12345678".getBytes(); //Í‥¹&KeyGeneratorÐγÉÒ&&&key System.out.println("\nStart generate AES key"); KeyGenerator keyGen=KeyGenerator.getInstance("AES"); keyGen.init(128); Key key=keyGen.generateKey(); System.out.println("Finish generating AES key"); //&&&ÃÒ&&&˽?¼ÓÃÜÀaCipher&&ECBÊǼÓÃÜ·½Ê½&&PKCS5PaddingÊÇÌ&³&·½·‥ Cipher cipher=Cipher.getInstance("AES/ECB/PKCS5Padding"); System.out.println("\n"+cipher.getProvider().getInfo()); //ʹÓÃ˽?¼ÓÃÜ 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,"UTF8")); 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,"UTF8")); } }

自己稍加修改的例子

Java代码
  1. byte[] plainText="12345678".getBytes();  
  2.   
  3.         //Í‥¹&KeyGeneratorÐγÉÒ&&&key  
  4.         System.out.println("\nStart generate AES key");  
  5.         KeyGenerator keyGen=KeyGenerator.getInstance("AES");  
  6.           
  7.         String pwd = "passord";  
  8.         keyGen.init(128new SecureRandom(pwd.getBytes()));  
  9.         //keyGen.init(128);  
  10.           
  11.         //Key key=keyGen.generateKey();  
  12.         SecretKey skey = keyGen.generateKey();  
  13.         byte[] raw = skey.getEncoded();  
  14.   
  15.         SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");  
  16.   
  17.         System.out.println("Finish generating AES key");  
  18.   
  19.         //&&&ÃÒ&&&˽?¼ÓÃÜÀaCipher&&ECBÊǼÓÃÜ
阅读(626) | 评论(1) | 转发(0) |
0

上一篇:设计模式分解java

下一篇:文件加密解密

给主人留下些什么吧!~~

chinaunix网友2010-11-24 14:41:01

很好的, 收藏了 推荐一个博客,提供很多免费软件编程电子书下载: http://free-ebooks.appspot.com