首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用JNCryptor加密InputStream

如何使用JNCryptor加密InputStream
EN

Stack Overflow用户
提问于 2013-04-09 23:18:01
回答 3查看 1.9K关注 0票数 0

我正在开发一个iPad应用程序,并使用RNCryptor在设备上进行加密和解密。这种加密格式的Java版本以JNCryptor的形式可用。

现在我有了要从InputStream读取的数据,但我希望在读取数据之前对数据进行加密。我找到了一个名为CipherInputStream的类,它似乎做了我想要做的事情。唯一的问题是,我需要一个Cipher (和Provider)来指定加密方法,但我不知道该怎么做。是否有可能定义自定义提供程序?

有没有人有关于使用JNCryptor加密InputStream的替代方法的建议?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-04-16 21:10:20

最后,我编写了一个类来读取InputStream,一次加密数据部分,并写入PipedOutputStream。然后,我将这个PipedOutputStream连接到一个PipedInputStream,并最终将其返回。加密和写入PipedOutputStream发生在单独的线程上,以避免死锁。

代码语言:javascript
复制
PipedInputStream pin = new PipedInputStream();
PipedOutputStream pout = new PipedOutputStream(pin);
EncryptionPipe pipe = new EncryptionPipe(5, pout, in, cipher, mac, metaData);
//EncryptionPipe(int interval, OutputStream out, InputStream in
//              ,Cipher cipher, Mac mac, byte[] metaData)
pipe.start();
return pin;

在EncryptionPipe中:

代码语言:javascript
复制
public class EncryptionPipe extends Thread {
    ...
    @Override
    public void run() {
        try {
            mac.update(metaData);
            out.write(metaData);

            byte[] buf = new byte[1024];
            int bytesRead = 0;
            byte[] crypted;
            byte[] hmac;
            while ((bytesRead = in.read(buf)) != -1) {
                if (bytesRead < buf.length) {
                    //the doFinal methods add padding if necessary, important detail!
                    crypted = cipher.doFinal(buf, 0, bytesRead);
                    hmac = mac.doFinal(crypted);

                    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                    bytes.write(crypted);
                    bytes.write(hmac);
                    crypted = bytes.toByteArray();
                    bytesRead = crypted.length;
                    bytes.close();
                } else {
                    crypted = cipher.update(buf, 0, bytesRead);
                    mac.update(crypted, 0, bytesRead);
                }
                out.write(crypted, 0, bytesRead);
                synchronized (this) {
                    this.wait(interval);
                }
            }
            out.close();
            ...
        }
    }
}
票数 1
EN

Stack Overflow用户

发布于 2014-08-24 21:41:45

JNCryptor v1.1.0昨天发布,并提供对流加密和解密的支持。

使用AES256JNCryptorInputStream进行解密,使用AES256JNCryptorOutputStream进行加密。

票数 1
EN

Stack Overflow用户

发布于 2013-04-09 23:26:41

您可以使用默认的Java提供程序。要实例化一个密码,您可以使用

代码语言:javascript
复制
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")

它使用AESCipher Block Chaining mode。CBC仅适用于16字节的倍数,因此您还指定了一种将输入填充为16字节的倍数的方法。

Here is some more sample AES code帮助您入门

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15905845

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档