3DES加密算法

3DES加密算法

使用原因

  • 最近和某财务系统对接,上传相关数据需要使用3DES加密传输json格式数据。

给定加密算法

  • “请求报文”字段需要使用3DES加密,加密方式为DES/CBC,输出BASE64编码格式,密钥由服务方通过其他方式分配。
  • key="XXXX";XXXX为32位(含大小写字母A-Z,a-z,数字0-9)
  • mode = CipherMode.CBC; 加密模式CBC
  • iv = "12345678" 偏移量

实际代码

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.SecureRandom;

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

import com.informix.base64.BASE64Decoder;
import com.informix.base64.BASE64Encoder;

public class EncryptUtils {
	/**
	 * 3DES加密
	 * 
	 * @param srcData,加密字符串
	 * @return
	 * @throws Exception
	 */
    //key 由对方给定,不唯一 
	public static final String PASSWORD_CRYPT_KEY = "SYzUP43duk0KWBc4X1KI4Sqs";
    //iv偏移量 由对方给定,不唯一
	public static final String PASSWORD_IV = "12345678";
   

	public static String desEncrypt(String srcData)
			throws Exception {
        //强随机数生成器
		SecureRandom sr = new SecureRandom();
        //调用给定32位key
		DESedeKeySpec dks = new DESedeKeySpec(PASSWORD_CRYPT_KEY.getBytes());
        //获取keyfactory 3DES输入值为DESede
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
        //由keyfactory生产出securekey
		SecretKey securekey = keyFactory.generateSecret(dks);
        //设置模式为CBC PKCS5Padding和PKCS7Padding 没发现区别 且参数 中只有PKCS5Padding可以调用
		Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
        //偏移量对象
		IvParameterSpec iv = new IvParameterSpec(PASSWORD_IV.getBytes());
        //初始化加密方法
		cipher.init(Cipher.ENCRYPT_MODE, securekey, iv, sr);
		byte[] doFinal = cipher.doFinal(srcData.getBytes());
		//由加密方法返回的是byte[] 数组 我这里输出方式为BASE64 需要格式化
        //hex格式化需要用以下代码 apache 下的格式化方法
        //return new String(Hex.encodeHex(cipher.doFinal(str.getBytes())));
		return new String(encode(doFinal));
	}

	public static void main(String[] args) {
		try {
			String aa = desEncrypt(
					"{\"ywlx\":\"PJFS\",\"ywnm\":\"190390000011\"}");
			System.out.println(aa + "结束");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * byte数组 转换为 Base64字符串
	 */
	public static String encode(byte[] data) {
		return new BASE64Encoder().encode(data);
	}

	/**
	 * Base64字符串 转换为 byte数组
	 */
	public static byte[] decode(String base64) {
		try {
			return new BASE64Decoder().decodeBuffer(base64);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return new byte[0];
	}

	/**
	 * 把文件内容编码为 Base64字符串, 只能编码小文件(例如文本、图片等)
	 */
	public static String encodeFile(File file) throws Exception {
		InputStream in = null;
		ByteArrayOutputStream bytesOut = null;

		try {
			in = new FileInputStream(file);
			bytesOut = new ByteArrayOutputStream((int) file.length());

			byte[] buf = new byte[1024];
			int len = -1;

			while ((len = in.read(buf)) != -1) {
				bytesOut.write(buf, 0, len);
			}
			bytesOut.flush();

			return encode(bytesOut.toByteArray());

		} finally {
			close(in);
			close(bytesOut);
		}
	}

	private static void close(Closeable c) {
		if (c != null) {
			try {
				c.close();
			} catch (IOException e) {
				// nothing
			}
		}
	}
}
posted @ 2021-03-17 15:19  最终还要远行  阅读(940)  评论(0)    收藏  举报