sd6733531 发表于 2013-2-3 12:36:40

位与加密方式的实现

位与加密方式的速度非常快。若能保证其私有密钥的安全性,则位与加密的安全性很高,要破译几乎是不可能的。
但是位与加密的缺陷是灵活性较差,对私有密钥的管理是个头疼的问题。
在只需要简单粗暴的加密方式的环境下,这是个不错的选择。
 
import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.util.Arrays;public class Encryptor {    public static byte[] encrypt(byte[] content, byte[] key) {      if (key.length == 0)            throw new IllegalArgumentException("key can not be empty!");      byte[] copy = Arrays.copyOf(content, content.length);      encrypt1(copy, key, 0);      return copy;    }    private static void encrypt1(byte[] content, byte[] key, int start) {      if (start == content.length)            return;// 递归结束条件      int end = start + key.length;      if (end >= content.length)            end = content.length;      for (int i = start; i < end; i++) {            content ^= key;      }      encrypt1(content, key, end);    }    public static byte[] decrypt(byte[] content, byte[] key) {      // 异或的解密等于加密      return encrypt(content, key);    }    public static void encryptFile(File file, File output, byte[] privateKey)            throws IOException {      if(output.getParentFile()!=null)            output.getParentFile().mkdirs();      FileInputStream fis = new FileInputStream(file);      FileOutputStream fos = new FileOutputStream(output);      byte[] buffer = new byte;      int realSize = -1;      try {            while ((realSize = fis.read(buffer)) != -1) {                byte[] encrypted = encrypt(buffer, privateKey);                fos.write(encrypted,0,realSize);            }      }      finally {            fos.close();            fis.close();      }    }    public static void decryptFile(File file, File output, byte[] privateKey)            throws IOException {      encryptFile(file, output, privateKey);    }    public static void main(String[] args) throws Exception {      byte[] key = "kiss".getBytes();      byte[] content = "dddefr12345adkfjsadfjladskfj".getBytes();      byte[] test = encrypt(content, key);      System.out.println(new String(test));      test = decrypt(test, key);      System.out.println(new String(test));//      encryptFile(new File("test"), new File("test2"), key);//      decryptFile(new File("test2"), new File("test3"), key);    }} 小弟潜水好久~出来透个气。呼呼
 
页: [1]
查看完整版本: 位与加密方式的实现