加解密:基於 java 實現 des ede3 cbc pkcs#5 算法

加解密:基於 java 實現 des ede3 cbc pkcs#5 算法

Code:

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;

public class test1280 {

	public static final byte[] KEY	= 
    {
		(byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0x90, (byte) 0xab, (byte) 0xcd, (byte) 0xef,
		(byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0x90, (byte) 0xab, (byte) 0xcd, (byte) 0xef,
		(byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0x90, (byte) 0xab, (byte) 0xcd, (byte) 0xef,
    };
	
	public static final byte[] IV	= 
	{
		(byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0x90, (byte) 0xab, (byte) 0xcd, (byte) 0xef,
	};
	
    /**
     * 十六進制打印字節數組
     * @param b byte[]
     */
    public static void printBytes(byte[] b)
    {
        for(int i=0;i<b.length;i++)
        {
            System.out.printf("%02x ", b[i]);
        }
        System.out.println();
    }

    public static void encrypt_des_ede_cbc_pkcs() throws Exception
    {
    	byte[] in = "test1280".getBytes("UTF-8");
    	Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
    	SecretKeyFactory skf = SecretKeyFactory.getInstance("DESede");
    	SecretKey sk = skf.generateSecret(new DESedeKeySpec(KEY));
    	IvParameterSpec ips = new IvParameterSpec(IV);
    	cipher.init(Cipher.ENCRYPT_MODE, sk, ips);
    	byte[] out = cipher.doFinal(in);
    	printBytes(out);
    }
    
    public static void decrypt_des_ede_cbc_pkcs() throws Exception
    {
    	byte[] out = 
    	{
    		(byte) 0x64, (byte) 0x5a, (byte) 0x6b, (byte) 0xd6, (byte) 0xbf, (byte) 0xf8, (byte) 0x36, (byte) 0xb2,
    		(byte) 0x4f, (byte) 0xd1, (byte) 0x74, (byte) 0xf6, (byte) 0xe7, (byte) 0xf6, (byte) 0xaf, (byte) 0xdb,
    	};
    	
    	Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
    	SecretKeyFactory skf = SecretKeyFactory.getInstance("DESede");
    	SecretKey sk = skf.generateSecret(new DESedeKeySpec(KEY));
    	IvParameterSpec ips = new IvParameterSpec(IV);
    	cipher.init(Cipher.DECRYPT_MODE, sk, ips);
    	byte[] in = cipher.doFinal(out);
    	printBytes(in);
    }
    
	public static void main(String[] args) throws Exception
	{
		// TODO Auto-generated method stub
		encrypt_des_ede_cbc_pkcs();
		decrypt_des_ede_cbc_pkcs();
	}

}

執行:

64 5a 6b d6 bf f8 36 b2 4f d1 74 f6 e7 f6 af db 
74 65 73 74 31 32 38 30 

等價的,基於 openssl 實現 des ede3 cbc pkcs#5 算法,請參見:

https://blog.csdn.net/test1280/article/details/105254483

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章