Java symmetric encryption

Source: Internet
Author: User
Tags asymmetric encryption

Java symmetric encryption

Recently, I am working on a User token function, learning encryption-related AES/DES, RSA, and so on. This involves symmetric and asymmetric encryption. Although symmetric encryption is not as secure as asymmetric encryption, the advantage is that encryption speed is fast, but in some cases, you can choose to use it, such as the current user cognitive mechanism, it is based on the token stateless and will be authenticated once upon each request. This requires a relatively high speed of encryption and decryption operations, so we chose the AES encryption method.

The following is a tool class for symmetric encryption, which can be independent of other third-party jar packages. However, I have encapsulated a base64 method (which will be added below ).

Import java. nio. charset. standardCharsets; import java. security. invalidKeyException; import java. security. noSuchAlgorithmException; import java. security. secureRandom; import javax. crypto. badPaddingException; import javax. crypto. cipher; import javax. crypto. illegalBlockSizeException; import javax. crypto. keyGenerator; import javax. crypto. noSuchPaddingException; import javax. crypto. secretKey; import com. ajaxjs. ut Il. encode;/*** symmetric ALGORITHM ** @ author admin **/public class extends riccipher {public extends riccipher () {} public extends riccipher (String ALGORITHM, int keySize) {this. ALGORITHM = ALGORITHM; this. keySize = keySize;}/*** DES = 56 | AES = 128 */private int keySize = 128;/*** encryption algorithm, DES | AES */private String ALGORITHM = "AES "; /*** encrypted ** @ param str * content to be encrypted * @ param key * @ return encrypted content */public Strin G encrypt (String str, String key) {// set it to UTF-8 here. Otherwise, if there is a mix of Chinese and English characters in the content, the decryption will be garbled. return doCipher (true, key, str, str. getBytes (StandardCharsets. UTF_8 ));} /*** decrypt ** @ param str * content to be decrypted * @ param key * @ return decrypted content */public String decrypt (String str, String key) {return doCipher (false, key, str, Encode. base64DecodeAsByte (str);} private String doCipher (boolean isENCRYPT_MODE, String key, String str, B Yte [] bytes) {Cipher cipher = null; try {cipher = Cipher. getInstance (ALGORITHM); cipher. init (isENCRYPT_MODE? Cipher. ENCRYPT_MODE: Cipher. DECRYPT_MODE, generateKey (key);} catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException e) {e. printStackTrace (); return null;} byte [] buf; try {// to prevent the javax from being decrypted. crypto. illegalBlockSizeException: Input length must // be multiple of 8 when decrypting with padded cipher exception, // The encrypted byte array cannot be directly converted into a string buf = cipher. doFinal (bytes);} catch (IllegalBlockSizeExcep Tion | BadPaddingException e) {e. printStackTrace (); return null;} return isENCRYPT_MODE? Encode. base64Encode (buf): Encode. byte2String (buf);}/*** obtain the key object ** @ param key * @ return key object */private SecretKey generateKey (String key) {SecureRandom secureRandom; keyGenerator kg; try {secureRandom = SecureRandom. getInstance ("SHA1PRNG"); secureRandom. setSeed (key. getBytes (); kg = KeyGenerator. getInstance (ALGORITHM);} catch (NoSuchAlgorithmException e) {e. printStackTrace (); return null;} kg. init (keySize, secureRandom); return kg. generateKey (); // generate key} final static response riccipher AES = new response riccipher (); final static response riccipher DES = new response riccipher ("DES", 56 ); /*** AES encryption ** @ param str * content to be encrypted * @ param key * @ return encrypted content */public static String AES_Encrypt (String str, string key) {return AES. encrypt (str, key);}/*** AES decryption * @ param str * @ param key * @ return */public static String AES_Decrypt (String str, String key) {return AES. decrypt (str, key );}}

The usage is as follows:

import org.junit.Test;import static org.junit.Assert.*;import com.ajaxjs.user.password.SymmetricCipher;public class TestPassword {String input = "cy11Xlbrmzyh:604:301:1353064296";String key = "37d5aed075525d4fa0fe635231cba447";@Testpublic void testEncryption() {String EncryptedPassword = SymmetricCipher.AES_Encrypt(input, key);//System.out.println("EncryptedPassword::" +EncryptedPassword);assertEquals(input, SymmetricCipher.AES_Decrypt(EncryptedPassword, key));}}

Base64 encoding and decoding method

Package com. ajaxjs. util; import java. io. IOException; import java. io. unsupportedEncodingException; import java.net. URLDecoder; import java.net. URLEncoder; import java. nio. charset. standardCharsets; import sun. misc. BASE64Decoder; import sun. misc. BASE64Encoder;/*** encoding and decryption of the string * @ author admin ***/public class Encode {/*** bytes are encoded as strings (UTF-8 encoding) ** @ param bytes * input byte array * @ return String */public static String Te2String (byte [] bytes) {return new String (bytes, StandardCharsets. UTF_8);}/*** convert String to UTF-8 encoded String *** @ param str * input String * @ return UTF-8 String */public static String byte2String (String str) {return byte2String (str. getBytes ();}/*** restores the URL-encoded characters, default UTF-8 encoding ** @ param str * URL-encoded String * @ return normal Java String */public static String urlDecode (String str) {try {return URLDecoder. decode (str, Standa RdCharsets. UTF_8.toString ();} catch (UnsupportedEncodingException e) {return null ;}/ *** encode the characters in a URL, the default UTF-8 encoding ** @ param str * normal Java String ** @ return URL-encoded String */public static String urlEncode (String str) {try {return URLEncoder. encode (str, StandardCharsets. UTF_8.toString ();} catch (UnsupportedEncodingException e) {return null ;}/ *** url Chinese garbled processing. * If the Tomcat filter is set to UTF-8, you do not need to transcode it again here ** @ param str * is usually the url Query String parameter * @ return Chinese */public static String urlChinese (String str) {return byte2String (str. getBytes (StandardCharsets. ISO_8859_1);}/*** BASE64 encoding * @ param bytes input byte array * @ return encoded String */public static String base64Encode (byte [] bytes) {return new BASE64Encoder (). encode (bytes);}/*** BASE64 encoding ** @ param str * string to be encoded * @ retur N encoded String */public static String base64Encode (String str) {return base64Encode (str. getBytes ();} public static byte [] base64DecodeAsByte (String str) {BASE64Decoder decoder = new BASE64Decoder (); try {return decoder. decodeBuffer (str);} catch (IOException e) {e. printStackTrace (); return null ;}/ *** BASE64 decoding requires forced exception capture. * Chinese garbled: http://s.yanghao.org/program/viewdetail.php? I = 54806 ** @ param str * decoded String * @ return decoded String */public static String base64Decode (String str) {return byte2String (base64DecodeAsByte (str ));}}
Java Learning Group 669823128

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.