簡體   English   中英

將Java AES / ECB / PKCS5填充加密為crypto-js解密

[英]Java AES/ECB/PKCS5Padding encryption to crypto-js decryption

后端使用下面的Java代碼進行AES加密。

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.xml.bind.DatatypeConverter;
import javax.crypto.spec.SecretKeySpec;

import java.security.MessageDigest;
import java.util.Arrays;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;



/**
 * This example program shows how AES encryption and decryption can be done in Java.
 * Please note that secret key and encrypted text is unreadable binary and hence 
 * in the following program we display it in hexadecimal format of the underlying bytes.
 * @author Jayson
 */
public class AESEncryption {

    /**
     * 1. Generate a plain text for encryption
     * 2. Get a secret key (printed in hexadecimal form). In actual use this must 
     * by encrypted and kept safe. The same key is required for decryption.
     * 3. 
     */
    public static void main(String[] args) throws Exception {


        String plainText = "rajaram";
        String keyText ="test123";
        SecretKey secKey = getSecretEncryptionKey(keyText);
         System.out.println("secKey:" + secKey);

        byte[] cipherText = encryptText(plainText, secKey);
        String decryptedText = decryptText(cipherText, secKey);

        System.out.println("Original Text:>>>> " + plainText);
        System.out.println("AES Key (Hex Form):>>>> "+bytesToHex(secKey.getEncoded()));
        System.out.println("Encrypted Text (Hex Form):>>>> "+bytesToHex(cipherText));
        System.out.println("Descrypted Text:>>>> "+decryptedText);

    }



  public static SecretKey getSecretEncryptionKey(String keyText) throws Exception {
        SecretKeySpec keySpec = new SecretKeySpec(getKey(keyText), "AES");
        return keySpec;
    }


  public static byte[] getKey(String keyStr) {
        byte[] key = null;
        try {
            key = (keyStr).getBytes("UTF-8");
            MessageDigest sha = MessageDigest.getInstance("SHA-1");
            key = sha.digest(key);
        System.out.println("SHA-1 key" + key);  
            key = Arrays.copyOf(key, 16);
        System.out.println("copyOf SHA-1 16 key" + key);        
        } catch (Exception e) {
            e.printStackTrace();
        }

     System.out.println("getKey" + key);
        return key;
    }

    /**
     * Encrypts plainText in AES using the secret key
     * @param plainText
     * @param secKey
     * @return
     * @throws Exception 
     */
    public static byte[] encryptText(String plainText,SecretKey secKey) throws Exception{
        // AES defaults to AES/ECB/PKCS5Padding in Java 7
        Cipher aesCipher = Cipher.getInstance("AES");

    System.out.println("ENCRYPT_MODE:" + Cipher.ENCRYPT_MODE);
        aesCipher.init(Cipher.ENCRYPT_MODE, secKey);
    System.out.println("plain Text getBytes:" + plainText.getBytes());
        byte[] byteCipherText = aesCipher.doFinal(plainText.getBytes());
    System.out.println("byte Cipher Text:" + byteCipherText);
        return byteCipherText;
    }

    /**
     * Decrypts encrypted byte array using the key used for encryption.
     * @param byteCipherText
     * @param secKey
     * @return
     * @throws Exception 
     */
    public static String decryptText(byte[] byteCipherText, SecretKey secKey) throws Exception {
        // AES defaults to AES/ECB/PKCS5Padding in Java 7
        Cipher aesCipher = Cipher.getInstance("AES");
        aesCipher.init(Cipher.DECRYPT_MODE, secKey);
        byte[] bytePlainText = aesCipher.doFinal(byteCipherText);
        return new String(bytePlainText);
    }

    /**
     * Convert a binary byte array into readable hex form
     * @param hash
     * @return 
     */
    private static String  bytesToHex(byte[] hash) {
        return DatatypeConverter.printHexBinary(hash);
    }
}

在Clas O / P之上:

getKey[B@6d06d69c
secKey:javax.crypto.spec.SecretKeySpec@fffe8c0a
ENCRYPT_MODE:1
plain Text getBytes:[B@34340fab
byte Cipher Text:[B@2aafb23c
Original Text:>>>> rajaram
AES Key (Hex Form):>>>> 7288EDD0FC3FFCBE93A0CF06E3568E28
Encrypted Text (Hex Form):>>>> 8E441411D9890BED64BD7931DE3230C3
Descrypted Text:>>>> rajaram

但是我無法使用crypto-js解密。

葉狀體的Crypto-js代碼示例:

var bytes = CryptoJS.AES.decrypt("8E441411D9890BED64BD7931DE3230C3", "test123", { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 });

var plaintext = bytes.toString(CryptoJS.enc.Utf8);
alert(plaintext);

JS小提琴鏈接: http : //jsfiddle.net/baxfk6tw/

任何人,crypto-js如何使用AES / ECB / PKCS5Padding添加SHA-1 16密鑰,請建議我如何解決此問題。

您的Java版本執行以下操作:

  • 使用SHA1哈希一次密碼,然后將前16個字節作為密鑰。
  • 使用AES-128,ECB模式,PKCS7填充對明文UTF-8字節進行加密。
  • 將密文轉換為十六進制。

因此,要使用CryptoJS對其解密 ,您需要重復相同的步驟:

 var ciphertext = CryptoJS.enc.Hex.parse("8E441411D9890BED64BD7931DE3230C3"); var pwhash = CryptoJS.SHA1(CryptoJS.enc.Utf8.parse("test123")); var key = CryptoJS.enc.Hex.parse(pwhash.toString(CryptoJS.enc.Hex).substr(0, 32)); var decrypted = CryptoJS.AES.decrypt({ ciphertext: ciphertext }, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 }); var plaintext = decrypted.toString(CryptoJS.enc.Utf8); $('#result').text(plaintext); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/crypto-js.js"></script> <h2 id="result"> 


作為參考,使用CryptoJS進行的加密可能如下所示:

 var plaintext = "rajaram"; var pwhash = CryptoJS.SHA1(CryptoJS.enc.Utf8.parse("test123")); var key = CryptoJS.enc.Hex.parse(pwhash.toString(CryptoJS.enc.Hex).substr(0, 32)); var encrypted = CryptoJS.AES.encrypt(plaintext, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 }); var ciphertext = encrypted.ciphertext.toString(CryptoJS.enc.Hex); $('#encrypted').text(ciphertext); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/crypto-js.js"></script> <h2 id="encrypted"> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM