网络安全

位置:IT落伍者 >> 网络安全 >> 浏览文章

AES对称加密例子


发布日期:2021年07月04日
 
AES对称加密例子

什么是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));

}

               

上一篇:JAVA语言安全行研究--Java的反编译

下一篇:webservice的安全机制---Filter