· 7 years ago · Aug 17, 2018, 02:02 AM
1Encrypt/Decrypt error on Mac OS
2public static String encrypt( String content, String password ) throws NoSuchAlgorithmException,
3 NoSuchPaddingException, UnsupportedEncodingException, InvalidKeyException, IllegalBlockSizeException,
4 BadPaddingException
5{
6 KeyGenerator kgen = KeyGenerator.getInstance( "AES" );
7 kgen.init( 128, new SecureRandom( password.getBytes() ) );
8 SecretKey secretKey = kgen.generateKey();
9 byte[] enCodeFormat = secretKey.getEncoded();
10 SecretKeySpec key = new SecretKeySpec( enCodeFormat, "AES" );
11 Cipher cipher = Cipher.getInstance( "AES" );
12 byte[] byteContent = content.getBytes( "utf-8" );
13 cipher.init( Cipher.ENCRYPT_MODE, key );
14 byte[] result = cipher.doFinal( byteContent );
15 return parseByte2HexStr( result );
16}
17
18
19public static String decrypt( String contents, String password ) throws NoSuchAlgorithmException,
20 NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException
21{
22 byte[] content = parseHexStr2Byte( contents );
23 KeyGenerator kgen = KeyGenerator.getInstance( "AES" );
24 kgen.init( 128, new SecureRandom( password.getBytes() ) );
25 SecretKey secretKey = kgen.generateKey();
26 byte[] enCodeFormat = secretKey.getEncoded();
27 SecretKeySpec key = new SecretKeySpec( enCodeFormat, "AES" );
28 Cipher cipher = Cipher.getInstance( "AES" );
29 cipher.init( Cipher.DECRYPT_MODE, key );
30 byte[] result = cipher.doFinal( content );
31 return new String( result );
32}
33
34
35public static String parseByte2HexStr( byte buf[] )
36{
37 StringBuffer sb = new StringBuffer();
38 for( int i = 0; i < buf.length; i++ )
39 {
40 String hex = Integer.toHexString( buf[i] & 0xFF );
41 if( hex.length() == 1 )
42 {
43 hex = '0' + hex;
44 }
45 sb.append( hex.toUpperCase() );
46 }
47 return sb.toString();
48}
49
50
51public static byte[] parseHexStr2Byte( String hexStr )
52{
53 if( hexStr.length() < 1 )
54 return null;
55 byte[] result = new byte[ hexStr.length() / 2 ];
56 for( int i = 0; i < hexStr.length() / 2; i++ )
57 {
58 int high = Integer.parseInt( hexStr.substring( i * 2, i * 2 + 1 ), 16 );
59 int low = Integer.parseInt( hexStr.substring( i * 2 + 1, i * 2 + 2 ), 16 );
60 result[i] = ( byte ) ( high * 16 + low );
61 }
62 return result;
63}