VUE aes暗号化、16進数列、base 64列を返す


VUE aes暗号化、16進数列、base 64列を返す
暗号化結果フォーマット
16        : 5AE0014CE35AF3CC9BF36BC0D7316A2B
base64      : WuABTONa88yb82vA1zFqKw==

1.vueコードは以下の通り
1.1 encryptUtils.js
// 1.    
// npm install crypto-js --save

// 2.    
// utils.js
import CryptoJS from 'crypto-js'

function encrypt(word, keyStr) {
     
  keyStr = keyStr || '0123456789ABCDEF'
  const key = CryptoJS.enc.Utf8.parse(keyStr)
  const srcs = CryptoJS.enc.Utf8.parse(word)
  const encrypted = CryptoJS.AES.encrypt(srcs, key, {
     
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  })
  return encrypted
}

export function decryptBase64(word, keyStr) {
     
  keyStr = keyStr || '0123456789ABCDEF'
  var key = CryptoJS.enc.Utf8.parse(keyStr)
  var decrypt = CryptoJS.AES.decrypt(word, key, {
     
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  })
  return CryptoJS.enc.Utf8.stringify(decrypt).toString()
}

export function encryptHex(word, keyStr) {
     
  const encrypted = encrypt(word, keyStr)
  return encrypted.ciphertext.toString().toUpperCase()
}

export function encryptBase64(word, keyStr) {
     
  const encrypted = encrypt(word, keyStr)
  return CryptoJS.enc.Base64.stringify(encrypted.ciphertext)
}

export function decryptHex(hexWord, keyStr) {
     
  const wordArray = CryptoJS.enc.Hex.parse(hexWord)
  const base64Word = CryptoJS.enc.Base64.stringify(wordArray)
  return decryptBase64(base64Word, keyStr)
}

1.2使用
import {
      encryptHex, encryptBase64, decryptBase64, decryptHex  } from 'encryptUtils'
 // BAE996B948645DA06922BE240FF3FEA1
console.log(encryptHex('123456'))
// uumWuUhkXaBpIr4kD/P+oQ==
console.log(encryptBase64('123456'))
// 123456
console.log(decryptBase64('uumWuUhkXaBpIr4kD/P+oQ=='))
// 123456
console.log(decryptHex('BAE996B948645DA06922BE240FF3FEA1'))

役に立つと思ったら、いいね!役に立つと思ったら、いいね!
役に立つと思ったら、いいね!役に立つと思ったら、いいね!
2.javaコードは次の通りです.
import com.alibaba.fastjson.JSONObject;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author :zhangbaoyu
 * @date :Created in 2020-04-30 10:56
 */
public class EncryptUtil {
     

    /**
     *     
     */
    private static final String ENCRY_ALGORITHM = "AES";

    /**
     *     /    /    
     *     AES  ,ECB    ,PKCS5Padding  
     */
    private static final String CIPHER_MODE = "AES/ECB/PKCS5Padding";

    /**
     *   iv   
     *     ECB    ,     iv   
     */
    private static final String IV_ = null;

    /**
     *        
     *      UTF-8    
     */
    private static final String CHARACTER = "UTF-8";

    /**
     *           。
     *       0;
     */
    private static final int PWD_SIZE = 16;

    /**
     *       
     *         ,
     *        ,          0  ,       
     *
     * @param password       
     * @return
     * @throws UnsupportedEncodingException
     */
    private static byte[] pwdHandler(String password) throws UnsupportedEncodingException {
     
        byte[] data = null;
        if (password != null) {
     
            byte[] bytes = password.getBytes(CHARACTER);
            if (password.length() < PWD_SIZE) {
     
                System.arraycopy(bytes, 0, data = new byte[PWD_SIZE], 0, bytes.length);
            } else {
     
                data = bytes;
            }
        }
        return data;
    }

    //======================>    <======================

    /**
     *     
     *
     * @param clearTextBytes       ,        
     * @param pwdBytes               
     * @return             ,      null
     */
    public static byte[] encrypt(byte[] clearTextBytes, byte[] pwdBytes) {
     
        try {
     
            // 1       
            SecretKeySpec keySpec = new SecretKeySpec(pwdBytes, ENCRY_ALGORITHM);

            // 2   Cipher  
            Cipher cipher = Cipher.getInstance(CIPHER_MODE);

            //            16(byte) * 8 =128 bit
//            System.out.println("     (byte):" + cipher.getBlockSize());

            // 3    Cipher  。            
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);

            // 4   
            byte[] cipherTextBytes = cipher.doFinal(clearTextBytes);

            // 5        
            return cipherTextBytes;

        } catch (NoSuchPaddingException e) {
     
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
     
            e.printStackTrace();
        } catch (BadPaddingException e) {
     
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
     
            e.printStackTrace();
        } catch (InvalidKeyException e) {
     
            e.printStackTrace();
        } catch (Exception e) {
     
            e.printStackTrace();
        }
        return null;
    }

    /**
     *     
     *
     * @param cipherTextBytes       ,        
     * @param pwdBytes                
     * @return             ,      null
     */
    public static byte[] decrypt(byte[] cipherTextBytes, byte[] pwdBytes) {
     

        try {
     
            // 1       
            SecretKeySpec keySpec = new SecretKeySpec(pwdBytes, ENCRY_ALGORITHM);

            // 2   Cipher  
            Cipher cipher = Cipher.getInstance(CIPHER_MODE);

            //            16(byte) * 8 =128 bit
//            System.out.println("     (byte):" + cipher.getBlockSize());

            // 3    Cipher  。            
            cipher.init(Cipher.DECRYPT_MODE, keySpec);

            // 4   
            byte[] clearTextBytes = cipher.doFinal(cipherTextBytes);

            // 5        
            return clearTextBytes;

        } catch (NoSuchAlgorithmException e) {
     
            e.printStackTrace();
        } catch (InvalidKeyException e) {
     
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
     
            e.printStackTrace();
        } catch (BadPaddingException e) {
     
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
     
            e.printStackTrace();
        } catch (Exception e) {
     
            e.printStackTrace();
        }
        //        null
        return null;
    }

    //======================>BASE64<======================

    /**
     * BASE64  
     *
     * @param clearText   ,      
     * @param password    ,     
     * @return     ,        。      null
     */
    public static String encryptBase64(String clearText, String password) {
     
        try {
     
            // 1           
            byte[] cipherTextBytes = encrypt(clearText.getBytes(CHARACTER), pwdHandler(password));

            // 2          BASE64 encoder    BASE6     
            BASE64Encoder base64Encoder = new BASE64Encoder();
            String cipherText = base64Encoder.encode(cipherTextBytes);

            // 3   BASE64     
            return cipherText;
        } catch (UnsupportedEncodingException e) {
     
            e.printStackTrace();
        } catch (Exception e) {
     
            e.printStackTrace();
        }
        //        null
        return null;
    }

    /**
     * BASE64  
     *
     * @param cipherText   ,      
     * @param password     ,     
     * @return     ,        。      null
     */
    public static String decryptBase64(String cipherText, String password) {
     
        try {
     
            // 1   BASE64       BASE64 decodebuffer         
            BASE64Decoder base64Decoder = new BASE64Decoder();
            byte[] cipherTextBytes = base64Decoder.decodeBuffer(cipherText);

            // 2                     
            byte[] clearTextBytes = decrypt(cipherTextBytes, pwdHandler(password));

            // 3    CHARACTER   ,       
            return new String(clearTextBytes, CHARACTER);
        } catch (UnsupportedEncodingException e) {
     
            e.printStackTrace();
        } catch (IOException e) {
     
            e.printStackTrace();
        } catch (Exception e) {
     
            e.printStackTrace();
        }
        //       null
        return null;
    }

    //======================>HEX<======================

    /**
     * HEX  
     *
     * @param clearText   ,      
     * @param password    ,     
     * @return     ,        。      null
     */
    public static String encryptHex(String clearText, String password) {
     
        try {
     
            // 1           
            byte[] cipherTextBytes = encrypt(clearText.getBytes(CHARACTER), pwdHandler(password));

            // 2               HEX    
            String cipherText = byte2hex(cipherTextBytes);

            // 3    HEX    
            return cipherText;
        } catch (UnsupportedEncodingException e) {
     
            e.printStackTrace();
        } catch (Exception e) {
     
            e.printStackTrace();
        }
        //       null
        return null;
    }

    /**
     * HEX  
     *
     * @param cipherText   ,      
     * @param password     ,     
     * @return     ,        。      null
     */
    public static String decryptHex(String cipherText, String password) {
     
        try {
     
            // 1  HEX             
            byte[] cipherTextBytes = hex2byte(cipherText);

            // 2                     
            byte[] clearTextBytes = decrypt(cipherTextBytes, pwdHandler(password));

            // 3    CHARACTER   ,       
            return new String(clearTextBytes, CHARACTER);
        } catch (UnsupportedEncodingException e) {
     
            e.printStackTrace();
        } catch (Exception e) {
     
            e.printStackTrace();
        }
        //       null
        return null;
    }

    /*      16       */
    public static String byte2hex(byte[] bytes) {
      //       ,
        StringBuffer sb = new StringBuffer(bytes.length * 2);
        String tmp = "";
        for (int n = 0; n < bytes.length; n++) {
     
            //           
            tmp = (Integer.toHexString(bytes[n] & 0XFF));
            if (tmp.length() == 1) {
     
                sb.append("0");
            }
            sb.append(tmp);
        }
        return sb.toString().toUpperCase(); //     
    }

    /* hex           */
    private static byte[] hex2byte(String str) {
     
        if (str == null || str.length() < 2) {
     
            return new byte[0];
        }
        str = str.toLowerCase();
        int l = str.length() / 2;
        byte[] result = new byte[l];
        for (int i = 0; i < l; ++i) {
     
            String tmp = str.substring(2 * i, 2 * i + 2);
            result[i] = (byte) (Integer.parseInt(tmp, 16) & 0xFF);
        }
        return result;
    }

    //    
    public static void main(String[] args) throws UnsupportedEncodingException {
     
        //    16 
        String key = "0123456789ABCDEF";
        //   
        String word = "123456";
        String encodeWordHex = encryptHex(word, key);
        String encodeWordBase64 = encryptBase64(word, key);

        //             hex    :BAE996B948645DA06922BE240FF3FEA1
        System.out.println("    hex    :" + encodeWordHex);
        //             base64    :uumWuUhkXaBpIr4kD/P+oQ==
        System.out.println("    base64    :" + encodeWordBase64);
    }
}

役に立つと思ったら、いいね!役に立つと思ったら、いいね!
役に立つと思ったら、いいね!役に立つと思ったら、いいね!