通过 javascript 加密并通过 Java 解密

我在我的反应本机应用程序中使用 AES 加密,如下所示


import CryptoJS from 'crypto-js' ;

encryptFun() {

    var data = "123456";

    var key  = CryptoJS.enc.Latin1.parse('1234567812345678');

    var iv   = CryptoJS.enc.Latin1.parse('1234567812345678');  

    var encrypted = CryptoJS.AES.encrypt(

      data,

      key,

      {iv:iv,mode:CryptoJS.mode.CBC,padding:CryptoJS.pad.ZeroPadding

    });

    console.log('encrypted: ' + encrypted) ;

    var decrypted = CryptoJS.AES.decrypt(encrypted,key,{iv:iv,padding:CryptoJS.pad.ZeroPadding});

    console.log('decrypted: '+decrypted.toString(CryptoJS.enc.Utf8));

  }

结果=加密:aK7+UX24ttBgfTnAndz9aQ==


以下是我在后端使用 java 进行解密的代码


 public static String desEncrypt() throws Exception {


        try

        {

            String data = "aK7+UX24ttBgfTnAndz9aQ==" ;

            String key = "1234567812345678";

            String iv = "1234567812345678";


            byte[] encrypted1 = new BASE64Decoder().decodeBuffer(data);


            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");

            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");

            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());


            cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);


            byte[] original = cipher.doFinal(encrypted1);

            String originalString = new String(original);

            return originalString;

        }

        catch (Exception e) {

            e.printStackTrace();

            return null;

        }

    }

输出=解密:= 123456[][][][][][][][][][]


我将其设置为 16 位,如上所述。我想要的是输出应该只有 123456。


慕尼黑8549860
浏览 304回答 3
3回答

ibeautiful

我建议你使用java.util.Base64解码。以下结果正确。我还建议使用修剪功能return originalString,看看是否有效。public class Decrypt {    public static void main(String[] args) {        try        {            String data = "aK7+UX24ttBgfTnAndz9aQ==" ;            String key = "1234567812345678";            String iv = "1234567812345678";            Decoder decoder = Base64.getDecoder();                byte[] encrypted1 = decoder.decode(data);            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());            cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);            byte[] original = cipher.doFinal(encrypted1);            String originalString = new String(original);            System.out.println(originalString.trim());        }        catch (Exception e) {            e.printStackTrace();        }    }}

摇曳的蔷薇

控制器部分生成 RSA 密钥(公共和私有)package com.secure.encryption.decryption.controller;import java.io.UnsupportedEncodingException;import java.nio.charset.StandardCharsets;import java.util.Base64;import java.util.Date;import java.util.HashMap;import java.util.Map;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.CrossOrigin;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RestController;import com.secure.encryption.decryption.rsa.keystore.KeyStore;import com.secure.encryption.decryption.rsa.service.RSAKeyPairGenerator;import com.secure.encryption.decryption.util.AesUtil;@RestControllerpublic class EncryptDecryptController {&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; @Autowired&nbsp; &nbsp; RSAKeyPairGenerator rsa;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; @Autowired&nbsp; &nbsp; KeyStore keystore;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; @CrossOrigin&nbsp; &nbsp; @GetMapping(value = "get/rsa/public")&nbsp; &nbsp; public Map<String, Object> generateRSA_PUBLIC_PRIVATE_KEY()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Map<String, Object> response = new HashMap<>();&nbsp; &nbsp; &nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;* Below function creates rsa public & private key&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;* While this api only share PUBLICKEY&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;* Whereas PRIVATEKEY is stored in bean/model&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; &nbsp; &nbsp; String public_KEY = null;&nbsp; &nbsp; &nbsp; &nbsp; public_KEY = rsa.KeyPairGenerator();&nbsp; &nbsp; &nbsp; &nbsp; response.put("public", public_KEY);&nbsp; &nbsp; &nbsp; &nbsp; return response;&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; @CrossOrigin&nbsp; &nbsp; @PostMapping(value = "/decrypt/AES_encyptedKEY/with/RSA_privateKEY/decryptdata/with/aes")&nbsp; &nbsp; public Map<String, Object> decrypt(@RequestBody Map<String, Object> req) throws UnsupportedEncodingException&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;* First decrypt AES-Key which is encrypted with RSA Public Key&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;* Use RSA privateKey for decryption&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; &nbsp; &nbsp; String Decrypted_AES_Key = rsa.decrypt(req.get("phrase").toString(),keystore.getPrivateKey());&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; byte[] decoded = Base64.getDecoder().decode(req.get("data").toString());&nbsp; &nbsp; &nbsp; &nbsp; String encryptedAES_Data = new String(decoded, StandardCharsets.UTF_8);&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;* Decode data to base 64&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;* Use AES key to decrypt the data&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; &nbsp; &nbsp; AesUtil aesUtil = new AesUtil(128, 1000);&nbsp; &nbsp; &nbsp; &nbsp; String decryptedAES_Data = aesUtil.decrypt(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; req.get("salt").toString(),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; req.get("iv").toString(),&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Decrypted_AES_Key,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; encryptedAES_Data);&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;* Map actual data as response&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; &nbsp; &nbsp; req.put("data", decryptedAES_Data);&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; return req;&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; @CrossOrigin&nbsp; &nbsp; @GetMapping(value = "/decryptfrom/backend/aes/plain/decrypt/frontend")&nbsp; &nbsp; public Map<String, Object> sendAESencryptedData()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;* Generate random key&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;* Encrypt data using same&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;* pass key to UI&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;* Decrypt using same key, iv and salt&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; &nbsp; &nbsp; Map<String, Object> response = new HashMap<>();&nbsp; &nbsp; &nbsp; &nbsp; int i = (int) (new Date().getTime()/1000);&nbsp; &nbsp; &nbsp; &nbsp; //String iv = generateIv().toString();&nbsp; &nbsp; &nbsp; &nbsp; AesUtil aesUtil = new AesUtil(128, 1000);&nbsp; &nbsp; &nbsp; &nbsp; String phrase = String.valueOf(i);//"my secret key 123";&nbsp; &nbsp; &nbsp; &nbsp; //String salt =&nbsp; new String(generateSalt(32));&nbsp; &nbsp; &nbsp; &nbsp; String iv = "bb6a69ace7a11a38fba164238e000c7c";&nbsp; &nbsp; &nbsp; &nbsp; String salt = "6c3674b6469467ab0b9f2b57ce36e78d";&nbsp; &nbsp; &nbsp; &nbsp; String encryptedAES_Data =&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Base64.getEncoder().encodeToString(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; aesUtil.encrypt(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; salt,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; iv,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; phrase,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "ganesha")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; response.put("data", encryptedAES_Data);&nbsp; &nbsp; &nbsp; &nbsp; response.put("salt", salt);&nbsp; &nbsp; &nbsp; &nbsp; response.put("iv", iv);&nbsp; &nbsp; &nbsp; &nbsp; response.put("key", phrase);&nbsp; &nbsp; &nbsp; &nbsp; return response;&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; /*&nbsp; &nbsp; public IvParameterSpec generateIv() {&nbsp; &nbsp; &nbsp; &nbsp; byte[] iv = new byte[16];&nbsp; &nbsp; &nbsp; &nbsp; new SecureRandom().nextBytes(iv);&nbsp; &nbsp; &nbsp; &nbsp; return new IvParameterSpec(iv);&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; private byte[] generateSalt(int size) {&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;byte[] salt = new byte[size];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; SecureRandom rand = SecureRandom.getInstance("SHA1PRNG");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; rand.nextBytes(salt);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return salt;&nbsp; &nbsp; &nbsp; &nbsp; } catch (Exception e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.err.println(e);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; }&nbsp; &nbsp; */&nbsp; &nbsp;&nbsp;}生成 RSA 随机密钥的服务package com.secure.encryption.decryption.rsa.service;public interface RSAKeyPairGenerator {&nbsp; &nbsp; public String KeyPairGenerator();&nbsp; &nbsp; public byte[] encrypt(String data, String publicKey);&nbsp; &nbsp; public String decrypt(String data, String base64PrivateKey);}实现类package com.secure.encryption.decryption.rsa.service;import java.security.InvalidKeyException;import java.security.KeyFactory;import java.security.KeyPair;import java.security.KeyPairGenerator;import java.security.NoSuchAlgorithmException;import java.security.PrivateKey;import java.security.PublicKey;import java.security.spec.InvalidKeySpecException;import java.security.spec.PKCS8EncodedKeySpec;import java.security.spec.X509EncodedKeySpec;import java.util.Base64;import java.util.HashMap;import java.util.Map;import javax.crypto.BadPaddingException;import javax.crypto.Cipher;import javax.crypto.IllegalBlockSizeException;import javax.crypto.NoSuchPaddingException;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import com.secure.encryption.decryption.rsa.keystore.KeyStore;@Servicepublic class RSAKeyPairGeneratorImpl implements RSAKeyPairGenerator{&nbsp; &nbsp; @Autowired&nbsp; &nbsp; KeyStore keystore;&nbsp; &nbsp; @Override&nbsp; &nbsp; public String KeyPairGenerator() {&nbsp; &nbsp; &nbsp; &nbsp; Map<String, Object> keypair = new HashMap<String, Object>();&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; keyGen.initialize(1024);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; KeyPair pair = keyGen.generateKeyPair();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; final String privatestring = Base64.getEncoder().encodeToString(pair.getPrivate().getEncoded());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; final String publicstring = Base64.getEncoder().encodeToString(pair.getPublic().getEncoded());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; keystore.setPrivateKey(privatestring);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return publicstring;&nbsp; &nbsp; &nbsp; &nbsp; } catch (Exception e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.err.println(e);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; private static PublicKey getPublicKey(String base64PublicKey){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; PublicKey publicKey = null;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; try{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(base64PublicKey.getBytes()));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; KeyFactory keyFactory = KeyFactory.getInstance("RSA");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; publicKey = keyFactory.generatePublic(keySpec);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return publicKey;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } catch (NoSuchAlgorithmException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } catch (InvalidKeySpecException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return publicKey;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; private static PrivateKey getPrivateKey(String base64PrivateKey){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; PrivateKey privateKey = null;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(base64PrivateKey.getBytes()));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; KeyFactory keyFactory = null;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; keyFactory = KeyFactory.getInstance("RSA");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } catch (NoSuchAlgorithmException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; privateKey = keyFactory.generatePrivate(keySpec);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } catch (InvalidKeySpecException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return privateKey;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; public byte[] encrypt(String data, String publicKey) {//throws BadPaddingException, IllegalBlockSizeException, InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException {&nbsp; &nbsp; &nbsp; &nbsp;try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //AES/CBC/PKCS5Padding&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //RSA/ECB/PKCS1Padding&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cipher.init(Cipher.ENCRYPT_MODE, getPublicKey(publicKey));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return cipher.doFinal(data.getBytes());&nbsp; &nbsp; &nbsp; &nbsp; } catch (Exception e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.err.println(e);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp;return null;&nbsp; &nbsp; }&nbsp; &nbsp; private static String decrypt(byte[] data, PrivateKey privateKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {&nbsp; &nbsp; &nbsp; &nbsp; Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");&nbsp; &nbsp; &nbsp; &nbsp; cipher.init(Cipher.DECRYPT_MODE, privateKey);&nbsp; &nbsp; &nbsp; &nbsp; return new String(cipher.doFinal(data));&nbsp; &nbsp; }&nbsp; &nbsp; public String decrypt(String data, String base64PrivateKey) {//throws IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException {&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return decrypt(Base64.getDecoder().decode(data.getBytes()), getPrivateKey(base64PrivateKey));&nbsp; &nbsp; &nbsp; &nbsp; } catch (InvalidKeyException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // TODO Auto-generated catch block&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; } catch (NoSuchPaddingException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // TODO Auto-generated catch block&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; } catch (NoSuchAlgorithmException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // TODO Auto-generated catch block&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; } catch (BadPaddingException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // TODO Auto-generated catch block&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; } catch (IllegalBlockSizeException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // TODO Auto-generated catch block&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; }}AesUtil 类package com.secure.encryption.decryption.util;import java.io.UnsupportedEncodingException;import java.security.InvalidAlgorithmParameterException;import java.security.InvalidKeyException;import java.security.NoSuchAlgorithmException;import java.security.spec.InvalidKeySpecException;import java.security.spec.KeySpec;import javax.crypto.BadPaddingException;import javax.crypto.Cipher;import javax.crypto.IllegalBlockSizeException;import javax.crypto.NoSuchPaddingException;import javax.crypto.SecretKey;import javax.crypto.SecretKeyFactory;import javax.crypto.spec.IvParameterSpec;import javax.crypto.spec.PBEKeySpec;import javax.crypto.spec.SecretKeySpec;import org.apache.commons.codec.DecoderException;import org.apache.commons.codec.binary.Hex;import org.apache.tomcat.util.codec.binary.Base64;public class AesUtil {&nbsp; &nbsp; private final int keySize;&nbsp; &nbsp; private final int iterationCount;&nbsp; &nbsp; private final Cipher cipher;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; public AesUtil(int keySize, int iterationCount) {&nbsp; &nbsp; &nbsp; &nbsp; this.keySize = keySize;&nbsp; &nbsp; &nbsp; &nbsp; this.iterationCount = iterationCount;&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; catch (NoSuchAlgorithmException | NoSuchPaddingException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw fail(e);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; public byte[] encrypt(String salt, String iv, String passphrase, String plaintext) {&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; SecretKey key = generateKey(salt, passphrase);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; byte[] encrypted = doFinal(Cipher.ENCRYPT_MODE, key, iv, plaintext.getBytes("UTF-8"));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(encrypted);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return encrypted;//Base64.getEncoder().encodeToString(encrypted);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //String s = Base64.getEncoder().encodeToString(encrypted);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; catch (UnsupportedEncodingException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw fail(e);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; public String decrypt(String salt, String iv, String passphrase, String ciphertext) {&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; SecretKey key = generateKey(salt, passphrase);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; byte[] decrypted = doFinal(Cipher.DECRYPT_MODE, key, iv, base64(ciphertext));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return new String(decrypted, "UTF-8");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; catch (UnsupportedEncodingException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; &nbsp; &nbsp; }catch (Exception e){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; private byte[] doFinal(int encryptMode, SecretKey key, String iv, byte[] bytes) {&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cipher.init(encryptMode, key, new IvParameterSpec(hex(iv)));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return cipher.doFinal(bytes);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; catch (InvalidKeyException&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; | InvalidAlgorithmParameterException&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; | IllegalBlockSizeException&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; | BadPaddingException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; private SecretKey generateKey(String salt, String passphrase) {&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; KeySpec spec = new PBEKeySpec(passphrase.toCharArray(), hex(salt), iterationCount, keySize);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; SecretKey key = new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return key;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; catch (NoSuchAlgorithmException | InvalidKeySpecException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; public static byte[] base64(String str) {&nbsp; &nbsp; &nbsp; &nbsp; return Base64.decodeBase64(str);&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; public static byte[] hex(String str) {&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return Hex.decodeHex(str.toCharArray());&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; catch (DecoderException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw new IllegalStateException(e);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; private IllegalStateException fail(Exception e) {&nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; }}遵循的步骤使用 RSA 密钥生成随机 AES(密钥、iv、盐)- 使用 crypto.js使用 AES 并加密易受攻击的数据使用RSA公钥加密AES密钥通过网络发送加密数据和密钥服务使用 AES 数据解密密钥使用AES密钥解密数据将数据发送回前端Html页面供参考<!DOCTYPE html><html><body>&nbsp; &nbsp; <script src="jquery.min.js"></script>&nbsp; &nbsp; &nbsp; &nbsp; <script src="jsencrypt.min.js"></script><script type="text/javascript" src="crypto-js.min.js"></script><script type="text/javascript" src="aes.js"></script><script type="text/javascript">const payloadsample = {&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; "addressLine1": "301,Kamala Mills Compound",&nbsp; &nbsp; &nbsp; &nbsp; "addressLine2": "Gr Flr, Tulsi Pipe Rd, Lower Parel ",&nbsp; &nbsp; &nbsp; &nbsp; "addressLine4": "Mumbai, Maharashtra",&nbsp; &nbsp; &nbsp; &nbsp; "zipcode": 400071};/**Step 1 ) - get data**//**Step 2 ) - get RSA pub Key**/function hybridEncryption(){&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; type: 'GET',//post&nbsp; &nbsp; &nbsp; &nbsp; url: 'http://localhost:1818/get/rsa/public',&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; success: function(res) {&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let RSAEncrypt = new JSEncrypt();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; RSAEncrypt.setPublicKey(res.public);//set RSA public key&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; const key = Math.random().toString(36).slice(2);//Generate random AES key&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log("key ", key);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var iv = CryptoJS.lib.WordArray.random(128/8).toString(CryptoJS.enc.Hex);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var salt = CryptoJS.lib.WordArray.random(128/8).toString(CryptoJS.enc.Hex);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var aesUtil = new AesUtil(128, 1000);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; debugger&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(key)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var data = JSON.stringify({ payloadsample });&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var ciphertext = aesUtil.encrypt(salt, iv, key, data);/**Step 3 ) - generate key&nbsp;**/&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; senData(RSAEncrypt, iv, salt, key, btoa(ciphertext))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; error:function(e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.error(e);&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; contentType: "application/json",&nbsp; &nbsp; &nbsp; &nbsp; dataType: 'json'&nbsp; &nbsp; });&nbsp; &nbsp;&nbsp;}function senData(RSAEncrypt, iv, salt, key, base64Content){&nbsp; &nbsp; &nbsp; &nbsp; const payload = {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "phrase":RSAEncrypt.encrypt(key),//encrypt with RSA&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "data":base64Content,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "iv":iv,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "salt":salt&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; console.log("sending : ", payload);&nbsp; &nbsp; &nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; type: 'POST',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; url: 'http://localhost:1818/decrypt/AES_encyptedKEY/with/RSA_privateKEY/decryptdata/with/aes',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data: JSON.stringify (payload), // or JSON.stringify ({name: 'jonas'}),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; success: function(data) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;console.log(data);&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; error:function(e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.error(e);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; contentType: "application/json",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dataType: 'json'&nbsp; &nbsp; &nbsp; &nbsp; });}&nbsp; &nbsp;hybridEncryption();/**&nbsp;* Incase of Backend encryption to Front end Decryption&nbsp;* decryptBE() - will get AES encrypted data with associated data&nbsp;* */function decryptBE(){&nbsp;&nbsp;&nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; type: 'GET',//post&nbsp; &nbsp; &nbsp; &nbsp; url: 'http://localhost:1818/decryptfrom/backend/aes/plain/decrypt/frontend',&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; success: function(res) {&nbsp; &nbsp; &nbsp; &nbsp; debugger&nbsp; &nbsp; &nbsp; &nbsp; var aesUtil = new AesUtil(128, 1000);&nbsp; &nbsp; &nbsp; &nbsp; var ciphertext = aesUtil.decrypt(res.salt, res.iv, res.key, res.data);&nbsp; &nbsp; &nbsp; console.log(ciphertext);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; error:function(e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.error(e);&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; contentType: "application/json",&nbsp; &nbsp; &nbsp; &nbsp; dataType: 'json'&nbsp; &nbsp; });}</script></body></html>&nbsp;这是一个使用参考的工作示例使用的其他库是 aes.jsvar AesUtil = function(keySize, iterationCount) {&nbsp; this.keySize = keySize / 32;&nbsp; this.iterationCount = iterationCount;};AesUtil.prototype.generateKey = function(salt, passPhrase) {&nbsp; var key = CryptoJS.PBKDF2(&nbsp; &nbsp; &nbsp; passPhrase,&nbsp;&nbsp; &nbsp; &nbsp; CryptoJS.enc.Hex.parse(salt),&nbsp; &nbsp; &nbsp; { keySize: this.keySize, iterations: this.iterationCount });&nbsp; return key;}AesUtil.prototype.encrypt = function(salt, iv, passPhrase, plainText) {&nbsp; var key = this.generateKey(salt, passPhrase);&nbsp; var encrypted = CryptoJS.AES.encrypt(&nbsp; &nbsp; &nbsp; plainText,&nbsp; &nbsp; &nbsp; key,&nbsp; &nbsp; &nbsp; { iv: CryptoJS.enc.Hex.parse(iv) });&nbsp; return encrypted.ciphertext.toString(CryptoJS.enc.Base64);}AesUtil.prototype.decrypt = function(salt, iv, passPhrase, cipherText) {&nbsp; var key = this.generateKey(salt, passPhrase);&nbsp; var cipherParams = CryptoJS.lib.CipherParams.create({&nbsp; &nbsp; ciphertext: CryptoJS.enc.Base64.parse(cipherText)&nbsp; });&nbsp; var decrypted = CryptoJS.AES.decrypt(&nbsp; &nbsp; &nbsp; cipherParams,&nbsp; &nbsp; &nbsp; key,&nbsp; &nbsp; &nbsp; { iv: CryptoJS.enc.Hex.parse(iv) });&nbsp; return decrypted.toString(CryptoJS.enc.Utf8);}其余的是JSEncrypt v2.3.1 https://npmcdn.com/jsencrypt@2.3.1/LICENSE.txt最后是 crypto-js.min.js谢谢,我希望这会有用

HUH函数

当您在 JS 中填充时,zeros您无法使用 解密NoPadding,解决方案是对数组或字符串进行操作修剪数组int i = original .length - 1; while (i >= 0 && original [i] == 0) {     --i; } return new String(Arrays.copyOf(original , i + 1));修剪字符串return new String(original).trim();手动删除zero值return new String(original).replace("\0", "");ZeroPAdding或者,因为Java 中似乎没有实现 ( Cipher Documentation),建议使用CryptoJS.pad.Pkcs
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java