ewighell
发贴: 0
积分: 0
|
于 2004-06-06 20:21
menzy wrote: 看看java的源程序。 c的源程序应当可以google到
楼上的,真的太感谢了 我根据你的程序作了两个类,果然很成功。你解了我的燃眉之急,谢谢你。 我做的两个也贴在这吧,所不定哪位会用到: 1. 把一个byte[] a 加密,返回加密后的byte[] import java.security.*; import javax.crypto.*; import javax.crypto.spec.*; public class encode{ public byte[] encode(byte[] a) { //添加新安全算法,如果用JCE就要把它添加进去 Security.addProvider(new com.sun.crypto.provider.SunJCE()); //final String Algorithm="DES"; //定义加密算法,可用 DES,DESede,Blowfish final String Algorithm = "DES/CBC/PKCS5Padding"; try { //生成密钥 byte[] bytes = {'e','+','s','u','%','*','4','O'}; byte[] key = new String("de$%^@#-").getBytes(); SecretKey deskey = new SecretKeySpec(key, "DES"); Cipher c1 = Cipher.getInstance (Algorithm); IvParameterSpec ivSpec = new IvParameterSpec (bytes); c1.init (Cipher.ENCRYPT_MODE, deskey, ivSpec); //加密 byte[] cipherByte=c1.doFinal; //cipherByte 为加密后的二进串 return cipherByte; } catch (java.security.NoSuchAlgorithmException e1) { e1.printStackTrace(); } catch (javax.crypto.NoSuchPaddingException e2) { e2.printStackTrace(); } catch (java.lang.Exception e3) { e3.printStackTrace(); } return null; } }
2. 将上一个类加密过的byte[]解密,返回解密后的byte[] import java.security.*; import javax.crypto.*; import javax.crypto.spec.*; public class decode{ public byte[] decode(byte[] a) { //添加新安全算法,如果用JCE就要把它添加进去 Security.addProvider(new com.sun.crypto.provider.SunJCE()); //final String Algorithm="DES"; //定义加密算法,可用 DES,DESede,Blowfish final String Algorithm = "DES/CBC/PKCS5Padding"; try { //生成密钥 byte[] bytes = {'e','+','s','u','%','*','4','O'}; byte[] key = new String("de$%^@#-").getBytes(); SecretKey deskey = new SecretKeySpec(key, "DES"); Cipher c1 = Cipher.getInstance (Algorithm); IvParameterSpec ivSpec = new IvParameterSpec (bytes); c1.init (Cipher.ENCRYPT_MODE, deskey, ivSpec); //解密 c1 = Cipher.getInstance(Algorithm); c1.init(Cipher.DECRYPT_MODE, deskey, ivSpec); byte[] clearByte=c1.doFinal; //clearByte为解密后的二进串 return clearByte; } catch (java.security.NoSuchAlgorithmException e1) { e1.printStackTrace(); } catch (javax.crypto.NoSuchPaddingException e2) { e2.printStackTrace(); } catch (java.lang.Exception e3) { e3.printStackTrace(); } return null; } }
|