Java使用指定随机种子加密解密

Java使用指定随机种子加密解密

一、加密

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.DESKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import static org.apache.commons.codec.binary.Hex.decodeHex;
import javax.crypto.*;
import java.security.spec.InvalidKeySpecException;

public class PasswordCipher {
    
    

    private static final String data =
            "a81dfab773f05633e755ce05af7347b130b0ac544b053889e04b1e195864d15bBA";

    //生成加密解密的随机种子
    public static String encrypt(String password) throws NoSuchAlgorithmException, DecoderException,
            InvalidKeyException, InvalidKeySpecException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException {
    
    
        byte[] key = decodeHex(data);
        //从原始密钥数据创建DESKeySpec对象
        DESKeySpec desKeySpec = new DESKeySpec(key);

        //创建一个密钥工厂,然后把DESKeySpec转换成SecretKey对象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);

        //cipher对象实际完成加密操作
        Cipher cipher = Cipher.getInstance("DES");

        //用密钥初始化Cipher对象
        cipher.init(Cipher.ENCRYPT_MODE,secretKey);

        byte[] bytes = cipher.doFinal(password.getBytes());

        return Hex.encodeHexString(bytes);

    }
}

二、解密

    public static String decrypt(String password) throws DecoderException, InvalidKeyException,
            NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException {
    
    
        byte[] key = decodeHex(data);
        //从原始密钥数据创建DESKeySpec对象
        DESKeySpec desKeySpec = new DESKeySpec(key);

        //创建一个密钥工厂,然后把DESKeySpec转换成SecretKey对象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);

        //cipher对象实际完成加密操作
        Cipher cipher = Cipher.getInstance("DES");

        //用密钥初始化Cipher对象
        cipher.init(Cipher.DECRYPT_MODE,secretKey);

        byte[] bytes = cipher.doFinal(Hex.decodeHex(password));

        return new String(bytes);

    }

三、主程序

        public static void main(String[] args){
    
    
        String data = "KTy_yT4g9w72";
        System.out.println("原始数据===>"+data);
        try {
    
    
            String encryptedPassword = encrypt(data);
            System.out.println("加密后===>"+encryptedPassword);
            String decryptPassword = decrypt(encryptedPassword);
            System.out.println("加密再次解密后的数据===>"+decryptPassword);
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
    }

Guess you like

Origin blog.csdn.net/zhengzaifeidelushang/article/details/121385342