不知道如何开始这个课程加密

时间:2015-02-18 18:49:36

标签: java encryption

我被赋予此类作为加密/解密的骨架示例,但我不知道如何开始这个,我仍然是java新手,我真的需要帮助。它应该有一个简单的加密算法,这个类应该有一个单独的文件中的3个其他子类,我已经完成了

import java.io.IOException;
public abstract class CryptStream
{
    protected StreamPair streams;
    /** Constructor 
     * @param theStreams a constructed StreamPair Instance
     */
    public CryptStream(StreamPair theStreams)
    {
    }
    /** Encrypt data in the byte array
     * @param data - the data to encrypt
     * @param len - how many bytes in the array to encrypt
     * @return a byte array with data encrypted. length may not be equal to
     * input
     */
    abstract protected byte [] cryptData( byte [] data, int len); 
    /** Decrypt data in the byte array
     * @param data - the data to decrypt
     * @param len - how many bytes in the array to decrypt
     * @return a byte array with data decrypted. length may not be equal to
     * input
     */
    abstract protected byte [] decryptData( byte [] data,int len);
    /** encrypt the input stream, and write to the output stream of 
     * of the StreamPair 
    *  @return number of bytes in output stream
    */
    public final int encrypt()
    {
        return 0; 
    }
    /** decrypt the input stream, and write to the output stream of 
     * of the StreamPair 
    *  @return number of bytes in output stream
    */
    public final int decrypt()
    {
        return 0; 
    }

}

1 个答案:

答案 0 :(得分:0)

我认为您需要设计类似于InputStreamReader / InputStreamWriter的类:

用于读取加密流扩展java.io.Reader类:

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;

public class EncryptedStreamReader extends Reader {
    private final InputStream in;
    private final String key;

    public EncryptedStreamReader(final InputStream in, final String key) {
        this.in = in;
        this.key = key;
    }

    @Override
    public int read(final char[] cbuf, final int off, final int len) throws IOException {
        //TODO all magic here
        return 0;
    }

    @Override
    public void close() throws IOException {
        in.close();
    }
}

这种方法有几个优点:

  • 遵循io子系统设计的常用java方法
  • 可以在没有任何额外代码的情况下在与Reader一起使用的地方使用(实际上它只是多态性的一个很好的例子)