您的位置:首页 > 编程语言 > Java开发

Java实现AES加密解密

2017-07-06 17:07 399 查看
转自http://blog.csdn.net/heqiangflytosky/article/details/51721122

public class AESUtils {

private static final String KEY_ALGORITHM = “AES”;

private static final Charset charset = Charset.forName( "utf-8" );

private static String decrypt( byte[] data, byte[] key ) {
try {
Key k = new SecretKeySpec( key, KEY_ALGORITHM );
Cipher cipher = Cipher.getInstance( KEY_ALGORITHM );
cipher.init( Cipher.DECRYPT_MODE, k );
return new String( cipher.doFinal( data ), charset );
} catch( Exception e ) {
throw new RuntimeException( e );
}
}

public static String decrypt( String data, String key ) {
return decrypt( parseHexStr2Byte( data ), key.getBytes( charset ) );
}

public static byte[] encrypt( byte[] data, byte[] key ) {
try {
Key k = new SecretKeySpec( key, KEY_ALGORITHM );
Cipher cipher = Cipher.getInstance( KEY_ALGORITHM );
cipher.init( Cipher.ENCRYPT_MODE, k );
return cipher.doFinal( data );
} catch( Exception e ) {
throw new RuntimeException( e );
}
}

public static String encrypt( String data, String key ) {
byte[] dataBytes = data.getBytes( charset );
byte[] keyBytes = key.getBytes( charset );
return parseByte2HexStr( encrypt( dataBytes, keyBytes ) );
}

public static byte[] parseHexStr2Byte( String hexStr ) {
byte[] result = new byte[ hexStr.length() / 2 ];
for( int i = 0; i < hexStr.length() / 2; i++ ) {
int high = Integer.parseInt( hexStr.substring( i * 2, i * 2 + 1 ), 16 );
int low = Integer.parseInt( hexStr.substring( i * 2 + 1, i * 2 + 2 ), 16 );
result[ i ] = ( byte )( high * 16 + low );
}
return result;
}

public static String parseByte2HexStr( byte buf[] ) {
StringBuilder sb = new StringBuilder();
for( int i = 0; i < buf.length; i++ ) {
String hex = Integer.toHexString( buf[ i ] & 0xFF );
if( hex.length() == 1 ) {
hex = '0' + hex;
}
sb.append( hex.toUpperCase() );
}
return sb.toString();
}


}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  加密 java 算法