Using AES with Java Technology

By Rags Srinivas
June 2003

In September 2000, the National Institute of Standards and Technology (NIST) approved the Federal Information Processing Standards (FIPS) 197(pdf 279.5 kb), culminating a multi-year effort to replace the out-of-date Data Encryption Standard (DES). As with DES, the new Advanced Encryption Standard (AES) should continue making inroads into private industry. This article looks at using AES in your Java programs.

What Is AES?

AES is a federal standard for private-key or symmetric cryptography. It supports combinations of key and block sizes of 128, 192, and 256. The algorithm chosen for this standard -- called Rijndael -- was invented by two Belgian cryptographers. As part of the evaluation process, the candidate algorithms (including Rijndael) were implemented in the Java language.

AES and Java Technology

The AES standard has been incorporated into several Java technology offerings. Beginning with the Java 2 SDK, Standard Edition (J2SE) v 1.4.0, the Java Cryptography Extension (JCE) was integrated with the SDK and the JRE. Since then, it has no longer been necessary to install the JCE optional package, since support for strong cryptography is now available as part of J2SE. JCE has a provider architecture that enables different providers to be plugged in under a common framework.

Several providers have supported AES in their own clean-room implementations of JCE, or under the existing framework. In Java 2 Platform, Standard Edition v 1.4.2, which is currently under beta, the Sun Provider, referred to as SunJCE, supports AES. Also, the Java Secure Socket Extension (JSSE) supports AES via JCE.

Finally, the Java Card specification version 2.2_01 supports AES with a 128-bit key size.

In this article, we will look primarily at AES support in J2SE, starting with JCE.

Using AES in JCE

Note: The programs listed in this article work only with Java 2 Platform, Standard Edition (J2SE) 1.4.2 installed.

You use AES like any other cipher. To see how, take a look at this JCE sample program. I've modified it to use AES, instead of Blowfish (another symmetric cipher). (I have changed occurrences of Blowfish to AES.)


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));
}
}

As you can see, the changes I made to accommodate AES are very minimal -- the JCE framework is very general and extensible.

This sample program demonstrates how to use strong cryptography, which is available by default in most installations. This does mean that support for larger key sizes is normally unavailable. To use AES with 192- and 256-bit key sizes, you need unlimited strength cryptography.

Strong Versus Unlimited Strength Cryptography

Due to import-control restrictions imposed by some countries, the jurisdiction policy files shipped with the Java 2 SDK, v 1.4 only permit strong cryptography to be used. An unlimited strength version of these files (that is, with no restrictions on cryptographic strength) is available for download, however.

After installing the unlimited strength version, to use key sizes of 192 and 256 bits, simply provide the required length of the key. The following line of code illustrates how to set the key size to 256 bits:


kgen.init(256); // 128 and 192 bits also available

The JCE examples given here show how to use AES for different key sizes, but they don't touch upon the more intricate issues -- like key management or key exchange algorithms. In practice, you may be more likely to use a protocol like Secure Socket Layer (SSL), which negotiates session keys using public keys that are subsequently used for bulk encryption.

Using AES in JSSE

Java Secure Socket Extension (JSSE) APIs are based around SSL, and the APIs are responsible for key negotiation and subsequent encryption and decryption. For a sample set of programs that illustrate the use of JSSE, see my earlier articles (listed in the See Also section, below). Since some of these articles are somewhat dated, note that the keyStore and trustStore entries will have to replaced by later versions of the corresponding files.

Some of the cipher suites may not be enabled for optimization of startup time. When SSLSockets are first created, no handshaking is done, so that applications can first set their communication preferences: which cipher suites to use, whether the socket should be in client or server mode, and so on. However, security is always provided by the time that application data is sent over the connection.

The getSupportedCipherSuites() method in SSLSocket returns all the possible suites that can be enabled for the connection. You can then use the setEnabledCipherSuites() to enable a subset of the available cipher suites, or to prioritize them. Use getEnabledCipherSuites() to return a list of all the enabled suites that are enabled by default, or that are set by a previous setEnabledCipherSuites() method call.

You can use the getCipherSuite() method in SSLSession to obtain the actual cipher used for the connection.

The following code illustrates the changes I made to the server program. The program uses regular expressions to prioritize AES encryption algorithms, with 256 bits as key size.


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);
}
}
}

Here is the corresponding client code:


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);
}
}
}

When running the server and the client, the output on the server side should be similar to the following:


Available Suites after Set:
TLS_RSA_WITH_AES_256_CBC_SHA
TLS_DHE_RSA_WITH_AES_256_CBC_SHA
TLS_DHE_DSS_WITH_AES_256_CBC_SHA
TLS_DH_anon_WITH_AES_256_CBC_SHA
SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA
SSL_DH_anon_EXPORT_WITH_RC4_40_MD5
SSL_DH_anon_WITH_DES_CBC_SHA
SSL_DH_anon_WITH_3DES_EDE_CBC_SHA
TLS_DH_anon_WITH_AES_128_CBC_SHA
SSL_DH_anon_WITH_RC4_128_MD5
SSL_RSA_WITH_NULL_SHA
SSL_RSA_WITH_NULL_MD5
SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA
SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA
SSL_RSA_EXPORT_WITH_DES40_CBC_SHA
SSL_RSA_EXPORT_WITH_RC4_40_MD5
SSL_DHE_DSS_WITH_DES_CBC_SHA
SSL_DHE_RSA_WITH_DES_CBC_SHA
SSL_RSA_WITH_DES_CBC_SHA
SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA
SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA
SSL_RSA_WITH_3DES_EDE_CBC_SHA
TLS_DHE_DSS_WITH_AES_128_CBC_SHA
TLS_DHE_RSA_WITH_AES_128_CBC_SHA
TLS_RSA_WITH_AES_128_CBC_SHA
SSL_RSA_WITH_RC4_128_SHA
SSL_RSA_WITH_RC4_128_MD5
Using cipher suite: TLS_RSA_WITH_AES_256_CBC_SHA

This output illustrates that the AES 256-bit algorithms are set to higher precedence than the other available algorithms. The cipher suite TLS_RSA_WITH_AES_256_CBC_SHAname constitutes the key negotiation, bulk encryption algorithms, and the key size, which in this case are RSA, AES and 256, respectively. SHA is used in the HMAC construction for integrity protection. By setting some of the debug output (as illustrated in my earlier article), you can get a peek into the inner workings of the different phases of the SSL algorithm.

Note: For performance reasons, it's probably not a good idea to enable all the supported algorithms, but I've included them here for illustration purposes.

Conclusion

The JCE framework is a very powerful and flexible framework for using different cryptographic algorithms. It's based on a provider architecture that enables the same framework to be used for newer cryptographic algorithms. From a developer perspective, this means a higher level of abstraction, and a common set of APIs for newer and different cryptographic algorithms -- without the need to worry about the inner workings of the algorithm.

Some of the other Java security APIs -- such as JSSE -- are implemented on top of JCE, and supplement it to make the different cryptographic algorithms (ciphers, Message Authentication Codes (MACs), and Key Exchange algorithms) available to in a more developer-friendly manner.

See Also

Java World article on AES

Java World article on Java Security optional packages (reprinted in java.sun.com)

AES home page

About the Author

Raghavan "Rags" Srinivas is a Java technology evangelist at Sun Microsystems, Inc. He specializes in Java technology and distributed systems. Srinivas has worked on several technology areas, including internals of VMS, UNIX® software, and NT.

AESwithJCE http://www.coderanch.com/how-to/content/AES_v1.html的更多相关文章

  1. requests的content与text导致lxml的解析问题

    title: requests的content与text导致lxml的解析问题 date: 2015-04-29 22:49:31 categories: 经验 tags: [Python,lxml, ...

  2. Content Security Policy 入门教程

    阮一峰文章:Content Security Policy 入门教程

  3. android 使用Tabhost 发生could not create tab content because could not find view with id 错误

    使用Tabhost的时候经常报:could not create tab content because could not find view with id 错误. 总结一下发生错误的原因,一般的 ...

  4. 【解决方案】cvc-complex-type.2.4.a: Invalid content was found starting with element 'init-param'. One of '{"http://java.sun.com/xml/ns/javaee":run-as, "http://java.sun.com/xml/ns/javaee":security-role-r

    [JAVA错误] cvc-complex-type.2.4.a: Invalid content was found starting with element 'init-param'. One o ...

  5. 注意 AppResLib.dll.*.mui 的生成操作应该为 Content

    为 Windows Phone 8 App 添加本地化的时候,发现修改 AppResLib.dll.*.mui 后不仅没有其变化,还发现修改它导致它失效.通过对比代码发现,问题原因是 AppResLi ...

  6. android Content Provider介绍

    ContentProvider(内容提供者)是Android中的四大组件之一.主要用于对外共享数据,也就是通过ContentProvider把应用中的数据共享给其他应用访问,其他应用可以通过Conte ...

  7. Jsoup问题---获取http协议请求失败 org.jsoup.UnsupportedMimeTypeException: Unhandled content type. Must be text/*, application/xml, or application/xhtml+xml.

    Jsoup问题---获取http协议请求失败 1.问题:用Jsoup在获取一些网站的数据时,起初获取很顺利,但是在访问某浪的数据是Jsoup报错,应该是请求头里面的请求类型(ContextType)不 ...

  8. css content之counter-reset、content-increment

    万万没想到,写了快三年前端,有不会用的css,居然还有完全没听过.见过的css属性,而且还是CSS2的内容! 关于counter-reset.content-increment两个属性的详解可以参看张 ...

  9. DOM解析XML报错:Content is not allowed in prolog

    报错内容为: Content is not allowed in prolog. Nested exception: Content is not allowed in prolog. 网上所述总结来 ...

随机推荐

  1. VC_MFC水波纹控件,开源

    代码和效果图: https://github.com/wjx0912/MfcWaterEffect 集成以下5个文件即可: watereffect\DIB.hwatereffect\DIB.cppwa ...

  2. Sublime Text 3常用快捷键

    收集的一些常用快捷键: 选择类 Ctrl+D 选中光标所占的文本,继续操作则会选中下一个相同的文本. Alt+F3 选中文本按下快捷键,即可一次性选择全部的相同文本进行同时编辑.举个栗子:快速选中并更 ...

  3. 转 https://www.zhihu.com/question/27606493/answer/37447829

    著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明出处.作者:梁川链接:https://www.zhihu.com/question/27606493/answer/37447829来源: ...

  4. BulkCopy频繁执行产生的性能问题

    问题现象: 完整的SQL脚本如下: from all_cons_columns acc, all_constraints ac where acc.owner = ac.owner and acc.c ...

  5. 利用pt-deadlock-logger监控死锁

    Percona提供的percona-toolkit提供很多实用功能,这里着重介绍如何监控死锁. pt-deadlock-logger基本用法 Usage: pt-deadlock-logger [OP ...

  6. SSAS处理时“找不到属性键”的解决办法 (转载)

    在SSAS中,经常会遇到“Attribute key not found(找不到属性键)”的错误,这种错误通常是由于某个维度属性(Dimension Attribute)的数据没能从Sql Serve ...

  7. 如何成为一名合格甚至优秀的个人草根站长(转载自ChinaZ)

    这章本来不想写来的,后来琢磨琢磨还是废话一下吧.主要是想说下现在草根站长的状态和如何成为一名合格的甚至优秀的草站站长. 伟大的草根站长们,在某些媒体的超级忽悠下全来到网络上淘金来了,有在校的大学生,有 ...

  8. WCF: 没有终结点在侦听可以接受消息的 这通常是由于不正确的地址或者 SOAP 操作导致的。

    问题:     由于我这里的wcf服务是采用“BasicHttpBinding”的方式,即安全绑定模式,客户端在引用这个服务后所生成的终结点配置(endpoint )就变成了<endpoint ...

  9. UE用法

    ueditor去除自动转换  ueditor在使用中发现很多问题.比如自动添加P标签,自动去除span,自动给li添加ul开始结束,自动把div转成P标签等等. 其实很多在百度上可以找到.这里总结下, ...

  10. 安装Yii框架时init.bat闪退的处理方法

    已经开启了php_openssl扩展还是会闪退 1.右击'计算机'-'属性'-'高级系统属性'-'环境变量(最下边)': 2.在'系统变量'里找到'path',双击,出现'编辑系统变量',在'变量值' ...