DES根据KEY加密,解密 工具类

// 这里的key 只能是八位

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class DESUtil {
	private static final byte[] iv = { 1, 2, 3, 4, 5, 6, 7, 8 };

	public static String encryptDES(String encryptString, String encryptKey)
			throws Exception {
		IvParameterSpec zeroIv = new IvParameterSpec(iv);
		SecretKeySpec key = new SecretKeySpec(encryptKey.getBytes(), "DES");
		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
		cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
		byte[] encryptedData = cipher.doFinal(encryptString.getBytes());
		return Base64.encode(encryptedData);
	}

	public static String decryptDES(String decryptString, String decryptKey)
			throws Exception {
		byte[] byteMi = Base64.decode(decryptString);
		IvParameterSpec zeroIv = new IvParameterSpec(iv);
		SecretKeySpec key = new SecretKeySpec(decryptKey.getBytes(), "DES");
		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
		cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);
		byte decryptedData[] = cipher.doFinal(byteMi);

		return new String(decryptedData);
	}
	
	public static String encrypt(String encryptString, String encryptKey)
			throws Exception {
		IvParameterSpec zeroIv = new IvParameterSpec(iv);
		SecretKeySpec key = new SecretKeySpec(encryptKey.getBytes(), "DES");
		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
		cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
		byte[] encryptedData = cipher.doFinal(encryptString.getBytes());
		return byteArr2HexStr(encryptedData);
	}

	public static String decrypt(String decryptString, String decryptKey)
			throws Exception {
		byte[] byteMi = hexStr2ByteArr(decryptString);
		IvParameterSpec zeroIv = new IvParameterSpec(iv);
		SecretKeySpec key = new SecretKeySpec(decryptKey.getBytes(), "DES");
		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
		cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);
		byte decryptedData[] = cipher.doFinal(byteMi);

		return new String(decryptedData);
	}
	
	 /**  
	   * 将byte数组转换为表示16进制值的字符串, 如:byte[]{8,18}转换为:0813, 和public static byte[]  
	   * hexStr2ByteArr(String strIn) 互为可逆的转换过程  
	   *   
	   * @param arrB  
	   *            需要转换的byte数组  
	   * @return 转换后的字符串  
	   * @throws Exception  
	   *             本方法不处理任何异常,所有异常全部抛出  
	   */
	  public static String byteArr2HexStr(byte[] arrB) throws Exception {
	    int iLen = arrB.length;
	    // 每个byte用两个字符才能表示,所以字符串的长度是数组长度的两倍   
	    StringBuffer sb = new StringBuffer(iLen * 2);
	    for (int i = 0; i < iLen; i++) {
	      int intTmp = arrB[i];
	      // 把负数转换为正数   
	      while (intTmp < 0) {
	        intTmp = intTmp + 256;
	      }
	      // 小于0F的数需要在前面补0   
	      if (intTmp < 16) {
	        sb.append("0");
	      }
	      sb.append(Integer.toString(intTmp, 16));
	    }
	    return sb.toString();
	  }

	  /**  
	   * 将表示16进制值的字符串转换为byte数组, 和public static String byteArr2HexStr(byte[] arrB)  
	   * 互为可逆的转换过程  
	   *   
	   * @param strIn  
	   *            需要转换的字符串  
	   * @return 转换后的byte数组  
	   * @throws Exception  
	   *             本方法不处理任何异常,所有异常全部抛出  
	   */
	  public static byte[] hexStr2ByteArr(String strIn) throws Exception {
	    byte[] arrB = strIn.getBytes();
	    int iLen = arrB.length;

	    // 两个字符表示一个字节,所以字节数组长度是字符串长度除以2   
	    byte[] arrOut = new byte[iLen / 2];
	    for (int i = 0; i < iLen; i = i + 2) {
	      String strTmp = new String(arrB, i, 2);
	      arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
	    }
	    return arrOut;
	  }
	
	public static void main(String[] args) {
		 try {
			 
			 String plaintext = "469123028@qq.com:1540104689043";
			 String key = "12345678";
			 String ciphertext = DESUtil.encryptDES(plaintext, key);
//			 String ciphertext = DESUtil.encrypt(plaintext, "zyqdkeys");
			 System.out.println("明文:" + plaintext);
			 System.out.println("密钥:" + key);
			 System.out.println("密文:" + ciphertext);
//			 System.out.println("解密后:" + DESUtil.decryptDES(ciphertext, "51zyqdap"));
//			 System.out.println("解密后:" + DESUtil.decrypt(ciphertext, "zyqdkeys"));
		
		 } catch (Exception e) {
			e.printStackTrace();
		}

	}
	
}


import java.awt.Graphics;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.FileImageOutputStream;
import javax.swing.ImageIcon;

public class Base64 {
	private static final char[] legalChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
			.toCharArray();
	/**
	 * 图片格式
	 * PNG
	 */
	public static final String IMAGE_TYPE_PNG = "png";

	/**
	 * 图片格式
	 * JPG
	 */
	public static final String IMAGE_TYPE_JPG = "jpg";
	
	/**
	 * data[]进行编码
	 * 
	 * @param data
	 * @return
	 */
	public static String encode(byte[] data) {
		int start = 0;
		int len = data.length;
		StringBuffer buf = new StringBuffer(data.length * 3 / 2);

		int end = len - 3;
		int i = start;
		int n = 0;

		while (i <= end) {
			int d = ((((int) data[i]) & 0x0ff) << 16)
					| ((((int) data[i + 1]) & 0x0ff) << 8)
					| (((int) data[i + 2]) & 0x0ff);

			buf.append(legalChars[(d >> 18) & 63]);
			buf.append(legalChars[(d >> 12) & 63]);
			buf.append(legalChars[(d >> 6) & 63]);
			buf.append(legalChars[d & 63]);

			i += 3;

			if (n++ >= 14) {
				n = 0;
				buf.append(" ");
			}
		}

		if (i == start + len - 2) {
			int d = ((((int) data[i]) & 0x0ff) << 16)
					| ((((int) data[i + 1]) & 255) << 8);

			buf.append(legalChars[(d >> 18) & 63]);
			buf.append(legalChars[(d >> 12) & 63]);
			buf.append(legalChars[(d >> 6) & 63]);
			buf.append("=");
		} else if (i == start + len - 1) {
			int d = (((int) data[i]) & 0x0ff) << 16;

			buf.append(legalChars[(d >> 18) & 63]);
			buf.append(legalChars[(d >> 12) & 63]);
			buf.append("==");
		}

		return buf.toString();
	}

	public static byte[] decode(String s) {

		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		try {
			decode(s, bos);
		} catch (IOException e) {
			throw new RuntimeException();
		}
		byte[] decodedBytes = bos.toByteArray();
		try {
			bos.close();
			bos = null;
		} catch (IOException ex) {
			System.err.println("Error while decoding BASE64: " + ex.toString());
		}
		return decodedBytes;
	}

	private static void decode(String s, OutputStream os) throws IOException {
		int i = 0;

		int len = s.length();

		while (true) {
			while (i < len && s.charAt(i) <= ' ')
				i++;

			if (i == len)
				break;

			int tri = (decode(s.charAt(i)) << 18)
					+ (decode(s.charAt(i + 1)) << 12)
					+ (decode(s.charAt(i + 2)) << 6)
					+ (decode(s.charAt(i + 3)));

			os.write((tri >> 16) & 255);
			if (s.charAt(i + 2) == '=')
				break;
			os.write((tri >> 8) & 255);
			if (s.charAt(i + 3) == '=')
				break;
			os.write(tri & 255);

			i += 4;
		}
	}

	private static int decode(char c) {
		if (c >= 'A' && c <= 'Z')
			return ((int) c) - 65;
		else if (c >= 'a' && c <= 'z')
			return ((int) c) - 97 + 26;
		else if (c >= '0' && c <= '9')
			return ((int) c) - 48 + 26 + 26;
		else
			switch (c) {
			case '+':
				return 62;
			case '/':
				return 63;
			case '=':
				return 0;
			default:
				throw new RuntimeException("unexpected code: " + c);
			}
	}
	
	/** 
	 * 将图片转换成二进制. <br/>
	 * @param  url,图片的存放 路径
	 * @return String,二进制字符串
	 * @throws exception
	 */
	public static String getImageBinary(String url){
	    File f = new File(url);
	    BufferedImage bi;
	    try {
	        bi = ImageIO.read(f);
	        ByteArrayOutputStream baos = new ByteArrayOutputStream();
	        ImageIO.write(bi, IMAGE_TYPE_PNG, baos);
	        byte[] bytes = baos.toByteArray();

	        return new String(org.apache.commons.codec.binary.Base64.encodeBase64Chunked(bytes)).trim();//encoder.encodeBuffer(bytes).trim();
	    } catch (IOException e) {
	        e.printStackTrace();
	    }    
	    return null;
	}
		
	/**
	 * 将二进制转换为图片,并保存. <br/>
	 * @param  base64String,图片的二进制字符串.
	 * @param  url,图片的保存 路径
	 * @return void
	 * @throws exception
	 */
	public static void base64StringToImage(String base64String, String url){
        try {    
            byte[] bytesArray = org.apache.commons.codec.binary.Base64.decodeBase64(base64String);//decoder.decodeBuffer(base64String);
            ByteArrayInputStream inputStream = new ByteArrayInputStream(bytesArray);
            BufferedImage bufferedImage =ImageIO.read(inputStream);
            File file = new File(url);
            //创建目录结构
            file.mkdirs();
            ImageIO.write(bufferedImage, IMAGE_TYPE_PNG, file);
        } catch (IOException e) {
            e.printStackTrace();
        }    
    }
	
	/**
     * 解码
     * 
     * @param inputString 待解码字符串
     * @return String 解码后字符串
     */
    public static String decodeStr(String inputString)
    {
        byte[] debytes = org.apache.commons.codec.binary.Base64.decodeBase64(new String(inputString).getBytes());
        return new String(debytes);
    }

	/**
     * 编码
     * 
     * @param inputString 待编码字符串
     * @return String 编码后字符串
     */
    public static String encodeStr(String inputString)
    {
        byte[] enbytes = org.apache.commons.codec.binary.Base64.encodeBase64Chunked(inputString.getBytes());
        return new String(enbytes);
    }
    
	/**
	 * Cavas截图上传.
	 * Base64转成图片 <br/>
	 * @param  base64String,图片的二进制字符串.
	 * @param  url,图片的保存 路径
	 * @return void
	 * @throws exception
	 */
	public static void cavasToImgFromBase64(String base64String, String url){
        try {    
            byte[] bytesArray = org.apache.commons.codec.binary.Base64.decodeBase64(base64String);
            ByteArrayInputStream inputStream = new ByteArrayInputStream(bytesArray);
            BufferedImage image =ImageIO.read(inputStream);
            
            // Image imageTookit = Toolkit.getDefaultToolkit().createImage(bytesArray); 
            // BufferedImage image = toBufferedImage(imageTookit);

        	// 生成目录
        	File file = new File(url);
        	File filePath = file.getParentFile();
            if (!filePath.isDirectory())  
            	filePath.mkdirs();
            if (!file.exists())  
                file.createNewFile();
            
            // ImageIO.write(image, IMAGE_TYPE_JPG, file);
            saveImageUsingJPGWithQuality(image, file.getAbsolutePath(), 1f);
        } catch (Exception e) {
            e.printStackTrace();
        }    
    }
	
	public static BufferedImage toBufferedImage(Image image) {
        if (image instanceof BufferedImage) {  
            return (BufferedImage) image;  
        }  
        // This code ensures that all the pixels in the image are loaded  
        image = new ImageIcon(image).getImage();  
        BufferedImage bimage = null;  
        GraphicsEnvironment ge = GraphicsEnvironment  
                .getLocalGraphicsEnvironment();  
        try {  
            int transparency = Transparency.OPAQUE;  
            GraphicsDevice gs = ge.getDefaultScreenDevice();  
            GraphicsConfiguration gc = gs.getDefaultConfiguration();
            bimage = gc.createCompatibleImage(image.getWidth(null),  
                    image.getHeight(null), transparency);  
        } catch (HeadlessException e) {  
            // The system does not have a screen  
        }  
        if (bimage == null) {  
            // Create a buffered image using the default color model  
            int type = BufferedImage.TYPE_INT_RGB;  
            bimage = new BufferedImage(image.getWidth(null),  
                    image.getHeight(null), type);  
        }  
        // Copy image to buffered image  
        Graphics g = bimage.createGraphics();  
        // Paint the image onto the buffered image  
        g.drawImage(image, 0, 0, null);  
        g.dispose();  
        return bimage;  
    } 
	
	/** 
     * save jpg with specified quality. 为了图片质量,quality的值不能太低。 
     * */  
    public static void saveImageUsingJPGWithQuality(BufferedImage image,  
            String filePath, float quality) throws Exception {  
  
        BufferedImage newBufferedImage = new BufferedImage(image.getWidth(),  
                image.getHeight(), BufferedImage.TYPE_3BYTE_BGR);  
        newBufferedImage.getGraphics().drawImage(image, 0, 0, null);  
  
        Iterator<ImageWriter> iter = ImageIO  
                .getImageWritersByFormatName("jpeg");  
  
        ImageWriter imageWriter = iter.next();  
        ImageWriteParam iwp = imageWriter.getDefaultWriteParam();  
  
        iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);  
        iwp.setCompressionQuality(quality);  
  
        File file = new File(filePath);  
        FileImageOutputStream fileImageOutput = new FileImageOutputStream(file);  
        imageWriter.setOutput(fileImageOutput);  
        IIOImage iio_image = new IIOImage(newBufferedImage, null, null);  
        imageWriter.write(null, iio_image, iwp);  
        imageWriter.dispose();  
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值