des


import java.security.Key;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

public class C {
	private Key getKey(String key) throws Exception {
		DESKeySpec dks = new DESKeySpec(key.getBytes());
		SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
		SecretKey sk = skf.generateSecret(dks);
		return sk;
	}

	public String initKey() throws Exception {
		SecureRandom sr = new SecureRandom();
		KeyGenerator kg = KeyGenerator.getInstance("DES");
		kg.init(sr);
		SecretKey sk = kg.generateKey();

		return new String(sk.getEncoded());
	}

	public byte[] encoder(byte[] date, String key) throws Exception {
		Key k = getKey(key);
		Cipher cip = Cipher.getInstance("DES");
		cip.init(cip.ENCRYPT_MODE, k);
		return cip.doFinal(date);
	}

	public byte[] decoder(byte[] date, String key) throws Exception {
		Key k = getKey(key);
		Cipher cip = Cipher.getInstance("DES");
		cip.init(cip.DECRYPT_MODE, k);
		return cip.doFinal(date);
	}

	public void test() {
		String aa = "我们";
		try {
			String key = initKey();
			System.out.println(key);
			byte[] input = encoder(aa.getBytes(), key);
			byte[] output = decoder(input, key);
			System.out.println(new String(input));
			System.out.println(new String(output));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		C c = new C();
		c.test();
	}
}

你可能感兴趣的:(C++,c,Security,C#)