java实现DES算法

public static void main(String []args) {
		long start = System.nanoTime();
		DESDataTransformer des = new DESDataTransformer("811");
		StringBuffer content = new StringBuffer();
		content.append("BEGIN:VCARD");
		content.append("VERSION:2.1");
		content.append("N;ENCODING=QUOTED-PRINTABLE;CHARSET=UTF-8:;=E6=AC=A7=E9=98=B3=E9=94=8B;;;");
		content.append("FN;ENCODING=QUOTED-PRINTABLE;CHARSET=UTF-8:=E6=AC=A7=E9=98=B3=E9=94=8B");
		content.append("TEL;CELL:13163209158");
		content.append("END:VCARD");
		
		try {
//			System.out.println(StringTools.getUTF8String(des.encode(StringTools.getUTF8Bytes(content.toString()))));
			byte [] decodeContent = des.decode(des.encode(StringTools.getUTF8Bytes(content.toString())));
			System.out.println(StringTools.getUTF8String(decodeContent));
		} catch (TransformerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("time=" + ((System.nanoTime() - start)/ (1000 * 1000)));
	}

	public DESDataTransformer(String key) {
		this(key, "des");
	}
	public DESDataTransformer(String key, String name) {
		super(key, name);
		// TODO Auto-generated constructor stub
	}

	@Override
	public byte[] encode(byte[] data) throws TransformerException {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(StringTools.getUTF8Bytes(this.key));
			byte[] keyBytes = md.digest();
			// create key
			DESKeySpec key = new DESKeySpec(keyBytes);
			SecretKeySpec DESKey = new SecretKeySpec(key.getKey(), "DES");
			// create cipher
			Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE, DESKey);
			// encrypt info
			return StringTools.getUTF8Bytes(StringTools.byte2hex(cipher.doFinal(data)));
		} catch (Exception e) {
			throw new TransformerException("Transformation error: ", e);
		}
	}

	@Override
	public String encode(String data) throws TransformerException {
		return StringTools.getUTF8String(encode(StringTools.getUTF8Bytes(data)));
	}

	@Override
	public byte[] decode(byte[] data) throws TransformerException {
		MessageDigest md;
		try {
			md = MessageDigest.getInstance("MD5");

			md.update(StringTools.getUTF8Bytes(this.key));
			byte[] keyBytes = md.digest();
			// create key
			DESKeySpec key = new DESKeySpec(keyBytes);
			SecretKeySpec DESKey = new SecretKeySpec(key.getKey(), "DES");
			// create cipher
			Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
			cipher.init(Cipher.DECRYPT_MODE, DESKey);
			// decrypt info
			return cipher.doFinal(StringTools.hex2byte(data));
		} catch (Exception e) {
			throw new TransformerException(e);
		}
	}

	@Override
	public String decode(String data) throws TransformerException {
		return StringTools.getUTF8String(decode(StringTools.getUTF8Bytes(data)));
	}



你可能感兴趣的:(java,exception,String,byte,Constructor,transformation)