package com.junmp.jyzb.utils;
import org.bouncycastle.crypto.BufferedBlockCipher;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.engines.DESedeEngine;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.util.encoders.Base64;

import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.spec.KeySpec;

public class EncryptionUtils {
    private static final String ENCRYPTION_ALGORITHM = "DESede";
    private static final String ENCRYPTION_KEY = "junmp";

    //Des加密
    public static String encryptDES(String message) throws Exception {
        byte[] keyBytes = ENCRYPTION_KEY.getBytes(StandardCharsets.UTF_8);
        KeySpec keySpec = new DESedeKeySpec(keyBytes);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ENCRYPTION_ALGORITHM);
        Key key = keyFactory.generateSecret(keySpec);

        BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new DESedeEngine());
        CipherParameters cipherParameters = new KeyParameter(key.getEncoded());

        cipher.init(true, cipherParameters);

        byte[] plaintext = message.getBytes(StandardCharsets.UTF_8);
        byte[] ciphertext = new byte[cipher.getOutputSize(plaintext.length)];
        int encryptedLength = cipher.processBytes(plaintext, 0, plaintext.length, ciphertext, 0);
        cipher.doFinal(ciphertext, encryptedLength);

        return new String(Base64.encode(ciphertext), StandardCharsets.UTF_8);
    }
}