繁体   English   中英

如何解密使用此代码加密的文本?

[英]How can I decrypt text encrypted using this code?

我在一个网站上找到了这段代码。 我无法理解如何解码。 你能帮助我吗?

import java.util.Base64;

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

public class AES {
    
    public static String encrypt(String strToEncrypt) throws Exception {
        byte[] plaintext = strToEncrypt.getBytes("UTF-8");
        KeyGenerator keygen = KeyGenerator.getInstance("AES");
        keygen.init(256);
        SecretKey key = keygen.generateKey();
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] ciphertext = cipher.doFinal(plaintext);
        return Base64.getEncoder().encodeToString(ciphertext);
    }

}

欢迎来到 Stackoverflow。 您可以在下面找到 AES CBC 字符串加密/解密的完整工作示例。 请注意,您需要将随机创建的密钥和初始化向量安全地存储到(稍后)加密的数据中,否则(真的)没有办法恢复您的数据。 加密和解密需要使用相同的密钥和iv。

由于密钥和 iv 是字节 arrays 我将它们编码为 Base64 以获得更好的存储。

安全警告:这是一个简单的示例,用于演示没有任何适当异常处理的 AES CBC 加密/解密。 该代码仅用于教育目的,不应在生产中使用!

结果:

AES CBC String Encryption with random key + iv
This is a simple example to demonstrate AES CBC en-/decryption without any proper exception handling.
The code is for educational purposes only and should not be used in production.

save the key and iv securely, without the data it will be NOT possible to decrypt !!
key in Base64-format: Nf41yG0F+MdFQnp3p3mIrWOk+2kxQ/LmyVcHKEKi5sQ=
iv in Base64-format:  yICmqsMaIdwsYsUDUsLWnA==
plaintext:     The quick brown fox jumps over the lazy dog
ciphertext:    PJNEV3H3Zh3TQx7B9jpg29gV59LgJ6baOpNM82dMOpPClJouYnq+hKVUQTDEkkdI
decryptedtext: The quick brown fox jumps over the lazy dog

代码:

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

public class AesCbcTextEncryptionRandomKeyIv {
    public static void main(String[] args) throws NoSuchPaddingException, InvalidKeyException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException {
        System.out.println("AES CBC String Encryption with random key + iv");
        System.out.println("This is a simple example to demonstrate AES CBC en-/decryption without any proper exception handling.");
        System.out.println("The code is for educational purposes only and should not be used in production.\n");

        String plaintext = "The quick brown fox jumps over the lazy dog";

        // generate a random key & initialization vector
        byte[] key = new byte[32]; // key for aes 256 encryption, 32 byte length
        byte[] iv = new byte[16]; // initialization vector with 16 byte length
        SecureRandom secureRandom = new SecureRandom();
        secureRandom.nextBytes(key);
        secureRandom.nextBytes(iv);
        System.out.println("save the key and iv securely, without the data it will be NOT possible to decrypt !!");
        // convert key & iv in base64 format for storage reasons
        String keyBase64 = Base64.getEncoder().encodeToString(key);
        String ivBase64 = Base64.getEncoder().encodeToString(iv);
        System.out.println("key in Base64-format: " + keyBase64);
        System.out.println("iv in Base64-format:  " + ivBase64);

        // encryption
        String ciphertext = encrypt(keyBase64, ivBase64, plaintext);
        System.out.println("plaintext:     " + plaintext);
        System.out.println("ciphertext:    " + ciphertext);

        // decryption
        String decryptedtext = decrypt(keyBase64, ivBase64, ciphertext);
        System.out.println("decryptedtext: " + decryptedtext);

    }
    public static String encrypt(String keyBase64, String ivBase64, String plaintext)
            throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException,
            InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.getDecoder().decode(keyBase64), "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(Base64.getDecoder().decode(ivBase64));
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
        return Base64.getEncoder().encodeToString(cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8)));
    }

    public static String decrypt(String keyBase64, String ivBase64, String ciphertext)
            throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException,
            InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.getDecoder().decode(keyBase64), "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(Base64.getDecoder().decode(ivBase64));
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
        return new String(cipher.doFinal(Base64.getDecoder().decode(ciphertext)), StandardCharsets.UTF_8);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM