- 浏览: 46671 次
- 性别:
- 来自: 北京
文章分类
最新评论
原文地址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代码
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));
}
}
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代码
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);
}
}
}
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代码
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);
}
}
}
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代码
/**
*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"));
}
}
/**
*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代码
byte[] plainText="12345678".getBytes();
//Í‥¹&KeyGeneratorÐγÉÒ&&&key
System.out.println("\nStart generate AES key");
KeyGenerator keyGen=KeyGenerator.getInstance("AES");
String pwd = "passord";
keyGen.init(128, new SecureRandom(pwd.getBytes()));
//keyGen.init(128);
//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");
//&&&ÃÒ&&&˽?¼ÓÃÜÀaCipher&&ECBÊǼÓÃÜE½Ê½&&PKCS5PaddingÊÇÌ&³&E½E‥
Cipher cipher=Cipher.getInstance("AES");
System.out.println("\n"+cipher.getProvider().getInfo());
//ʹÓÃ˽?¼ÓÃÜ
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,"UTF8"));
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,"UTF8"));
}
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代码
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));
}
}
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代码
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);
}
}
}
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代码
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);
}
}
}
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代码
/**
*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"));
}
}
/**
*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代码
byte[] plainText="12345678".getBytes();
//Í‥¹&KeyGeneratorÐγÉÒ&&&key
System.out.println("\nStart generate AES key");
KeyGenerator keyGen=KeyGenerator.getInstance("AES");
String pwd = "passord";
keyGen.init(128, new SecureRandom(pwd.getBytes()));
//keyGen.init(128);
//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");
//&&&ÃÒ&&&˽?¼ÓÃÜÀaCipher&&ECBÊǼÓÃÜE½Ê½&&PKCS5PaddingÊÇÌ&³&E½E‥
Cipher cipher=Cipher.getInstance("AES");
System.out.println("\n"+cipher.getProvider().getInfo());
//ʹÓÃ˽?¼ÓÃÜ
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,"UTF8"));
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,"UTF8"));
}
发表评论
-
java加密算法介绍
2011-05-20 14:06 1044参考: http://justsee.javaeye. ... -
JAVA加密算法(RSA)
2011-05-20 13:51 1234RSA 这种算法1978年就出现了,它是第一个既能用 ... -
JAVA加密算法(BASE64,MD5,SHA)
2011-05-20 13:46 3232这三种加密算法,可谓是非可逆加密,就是不可解密的加密方法。 ... -
JAVA加密算法(DES)
2011-05-20 13:41 1623DES DES-Data Encryption Standa ... -
JAVA加密算法(ECC )
2011-05-20 13:34 3209ECC-Elliptic Curves Cryptograph ... -
JAVA加密算法(DSA)
2011-05-20 13:33 6165接下来我们介绍DSA数字签名,非对称加密的另一种实现。 ... -
JAVA加密算法(DH)
2011-05-20 13:32 1865接下来我们分析DH加密算法,一种适用于网络交互的加密算法。 ... -
文件加密解密
2011-05-20 13:31 1060/** * 加密文件infilename,输出加密 ... -
关JAVA加密算法的实现实例(基础知识)
2011-05-20 13:30 981基础知识 如基本的单向加密算法: BASE64 MD5 ... -
java加密算法(综合)
2011-05-20 13:27 967对象 参数 algorithm 如:"DSA&quo ... -
java加密算法(MD5withRSA)
2011-05-20 13:24 8947一、前言: 网络 ...
相关推荐
主要介绍了Java实现的对称加密算法AES,结合实例形式分析了对称加密算法AES的定义、特点、用法及使用场景,需要的朋友可以参考下
AES高级加密标准,在密码学中又称Rijndael加密法,是美国联邦政府采用的一种...本软件是用java语言开发,实现了AES算法对文件的加密和解密,并在界面上加了进度条,来提示用户加密解密的进度。如果不足之处,欢迎留言。
java加密算法AES\DES\RSA示例及常用知识学习杂记
Java实现AES加密算法Java实现AES加密算法
AES加密算法的JAVA实现(只有加密)
Java 加密解密之对称加密算法AES.docx
java加密算法(aes+des+pboc3des+pbocdes等)
主要介绍了java实现的AES加密算法,结合完整实例形式分析了AES加密类的实现技巧,具有一定参考借鉴价值,需要的朋友可以参考下
JAVA实现AES加密算法代码.doc
AES算法的实现过程,实现了AES的加密和解密过程
JAVA AES 加密算法 javax.crypto.Cipher AES/ECB/PKCS5Padding
VB6-AES加密算法源码,无错,可直接运行。密钥长度支持128 Bit,192 Bit,256 Bit。支持字符串加密和文件加密。
本文就简单介绍如何通过JAVA实现AES加密: /** * 测试AES加密和解密 * @param args */ public static void main(String[] args) { /**数据初始化**/ String content = "http://www.mbaike.net"; String...
Java版AES加密算法,亲测可用
java关于加密的算法demo代码(Base64加密\数字签名\对称加密算法\非对称加密算法\消息摘要算法) JAVA安全实现三种方式: 1.JDK 2.Commons Codec 3.Bouncy Castle 一。非对称加密算法: 1.DH 2.RSA 3.ELGamal 二。...
NULL 博文链接:https://renfj.iteye.com/blog/2086421
java加密算法源码 包括有AES DES MD5 RSA SHA加密和解密
基于网上的JavaScript代码和标准AES算法改进,可实现JavaScript和Java的AES/128/192/256位加密解密互操作。
AES 算法模式 密钥长度 密钥 密钥偏移量 补码方式 加密结果编码方式,支持以上参数,支持2进制转16进制,二进制转Hbase64加密方式以及解密方式
在工作中会经常遇到密码加密,URL传参要进行加密,在此我参照一个例子将用java实现的AES加解密程序用实例写出。JS实现AES-GCM加密,java实现AES-GCM解密