图像文件的加密与解密

2024-03-10

结合我的另一个question https://stackoverflow.com/questions/12131627/image-encryption-decryption,并且在更改了这一小部分代码之后

FileOutputStream output = new FileOutputStream("sheepTest.png");
    CipherOutputStream cos = new CipherOutputStream(output, pbeCipher);
    ImageIO.write(input, "PNG", cos);
    cos.close();

从解密部分,我遇到了另一个错误,这是

Exception in thread "main" java.lang.IllegalArgumentException: image == null!
at javax.imageio.ImageTypeSpecifier.createFromRenderedImage(Unknown Source)
at javax.imageio.ImageIO.getWriter(Unknown Source)
at javax.imageio.ImageIO.write(Unknown Source)
at encypt.com.trial.main(trial.java:82)

当我单击sheepTest.png时,该文件是空的。错误在哪里?谁能帮我解决这个错误?谢谢。

public class trial {
public static void main(String[] arg) throws Exception {

   // Scanner to read the user's password. The Java cryptography
   // architecture points out that strong passwords in strings is a
   // bad idea, but we'll let it go for this assignment.
   Scanner scanner = new Scanner(System.in);
   // Arbitrary salt data, used to make guessing attacks against the
   // password more difficult to pull off.
   byte[] salt = { (byte) 0xc7, (byte) 0x73, (byte) 0x21, (byte) 0x8c,
           (byte) 0x7e, (byte) 0xc8, (byte) 0xee, (byte) 0x99 };

   {
     File inputFile = new File("sheep.png");
      BufferedImage input = ImageIO.read(inputFile);
      Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
      SecretKeyFactory keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
     // Get a password from the user.
     System.out.print("Password: ");
     System.out.flush();
     PBEKeySpec pbeKeySpec = new PBEKeySpec(scanner.nextLine().toCharArray());          
     // Set up other parameters to be used by the password-based
     // encryption.
     PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, 20);
     SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
     // Make a PBE Cyhper object and initialize it to encrypt using
     // the given password.
     Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
     pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
     FileOutputStream output = new FileOutputStream("sheepTest.png");
     CipherOutputStream cos = new CipherOutputStream(
            output, pbeCipher);
       //File outputFile = new File("image.png");
         ImageIO.write(input,"PNG",cos);
      cos.close();          

   }
   // Now, create a Cipher object to decrypt for us. We are repeating
   // some of the same code here to illustrate how java applications on
   // two different hosts could set up compatible encryption/decryption
   // mechanisms.
  {
       File inputFile = new File("sheepTest.png");
         BufferedImage input = ImageIO.read(inputFile);
       // Get another (hopefully the same) password from the user.
      System.out.print("Decryption Password: ");
       System.out.flush();
       PBEKeySpec pbeKeySpec = new PBEKeySpec(scanner.next().toCharArray());
       // Set up other parameters to be used by the password-based
       // encryption.
       PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, 20);
       SecretKeyFactory keyFac = SecretKeyFactory
               .getInstance("PBEWithMD5AndDES");
       SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
       // Make a PBE Cyper object and initialize it to decrypt using
       // the given password.
       Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
       pbeCipher.init(Cipher.DECRYPT_MODE, pbeKey, pbeParamSpec);
       // Decrypt the ciphertext and then print it out.
       /*byte[] cleartext = pbeCipher.doFinal(ciphertext);
       System.out.println(new String(cleartext));*/
       FileOutputStream output = new FileOutputStream("sheepTest.png");
       CipherOutputStream cos = new CipherOutputStream(
              output, pbeCipher);
        ImageIO.write(input,"PNG",  cos);
        cos.close();

   }
   }
}

继 NateCK 富有洞察力的帖子(顺便说一句,做得很好)之后,我修改了您的解密部分

// Note that we are not reading the image in here...
System.out.print("Decryption Password: ");
System.out.flush();
PBEKeySpec pbeKeySpec = new PBEKeySpec(scanner.next().toCharArray());
// Set up other parameters to be used by the password-based
// encryption.
PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, 20);
SecretKeyFactory keyFac = SecretKeyFactory
        .getInstance("PBEWithMD5AndDES");
SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
// Make a PBE Cyper object and initialize it to decrypt using
// the given password.
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
pbeCipher.init(Cipher.DECRYPT_MODE, pbeKey, pbeParamSpec);

// We're now going to read the image in, using the cipher
// input stream, which wraps a file input stream
File inputFile = new File("sheepTest.png");
FileInputStream fis = new FileInputStream(inputFile);
CipherInputStream cis = new CipherInputStream(fis, pbeCipher);
// We then use all that to read the image
BufferedImage input = ImageIO.read(cis);
cis.close();

// We then write the dcrypted image out...
// Decrypt the ciphertext and then print it out.
FileOutputStream output = new FileOutputStream("sheepTest.png");
ImageIO.write(input, "PNG", output);

我的例子基于 NateCKs 的发现。如果你觉得它有用,点个赞就好了,但 NateCK 值得称赞;)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

图像文件的加密与解密 的相关文章

  • 正则表达式拆分数字和字母组,不带空格

    如果我有一个像 11E12C108N 这样的字符串 它是字母组和数字组的串联 如何在中间没有分隔符空格字符的情况下分割它们 例如 我希望分割结果为 tokens 0 11 tokens 1 E tokens 2 12 tokens 3 C
  • 如何使用 Java 处理 Selenium WebDriver 中的新窗口?

    这是我的代码 driver findElement By id ImageButton5 click Thread sleep 3000 String winHandleBefore driver getWindowHandle drive
  • 按第一列排序二维数组,然后按第二列排序

    int arrs 1 100 11 22 1 11 2 12 Arrays sort arrs a b gt a 0 b 0 上面的数组已排序为 1 100 1 11 2 12 11 22 我希望它们按以下方式排序a 0 b 0 首先 如果
  • 如何在不超过最大值的情况下增加变量?

    我正在为学校开发一个简单的视频游戏程序 我创建了一个方法 如果调用该方法 玩家将获得 15 点生命值 我必须将生命值保持在最大值 100 并且由于我目前的编程能力有限 我正在做这样的事情 public void getHealed if h
  • 当从服务类中调用时,Spring @Transactional 不适用于带注释的方法

    在下面的代码中 当方法内部 是从内部调用的方法外部 应该在交易范围内 但事实并非如此 但当方法内部 直接从调用我的控制器class 它受到事务的约束 有什么解释吗 这是控制器类 Controller public class MyContr
  • 如何使使用 css 调整大小的图像在 IE 中看起来不错?

    当使用 css 宽度 高度或属性宽度 高度缩放图像时 IE6 和 IE7 无法很好地缩放网页中的图像 我不确定它默认使用哪种算法 但这不好 在这些浏览器中缩放时 缩放图像会显示锯齿伪影 幸运的是 有一种方法可以通过简单的 css 规则强制
  • Calendar.getInstance(TimeZone.getTimeZone("UTC")) 不返回 UTC 时间

    我对得到的结果真的很困惑Calendar getInstance TimeZone getTimeZone UTC 方法调用 它返回 IST 时间 这是我使用的代码 Calendar cal Two Calendar getInstance
  • Java 8 流 - 合并共享相同 ID 的对象集合

    我有一系列发票 class Invoice int month BigDecimal amount 我想合并这些发票 这样我每个月都会收到一张发票 金额是本月发票金额的总和 例如 invoice 1 month 1 amount 1000
  • Java 中的“Lambdifying”scala 函数

    使用Java和Apache Spark 已用Scala重写 面对旧的API方法 org apache spark rdd JdbcRDD构造函数 其参数为 AbstractFunction1 abstract class AbstractF
  • 普罗米修斯指标 - 未找到

    我有 Spring Boot 应用程序 并且正在使用 vertx 我想监控服务和 jvm 为此我选择了 Prometheus 这是我的监控配置类 Configuration public class MonitoringConfig Bea
  • Java整数双除法混淆[重复]

    这个问题在这里已经有答案了 方案1 int sum 30 double avg sum 4 result is 7 0 not 7 5 VS 方案2 int sum 30 double avg sum 4 0 Prints lns 7 5
  • 如何知道抛出了哪个异常

    我正在对我们的代码库进行审查 有很多这样的陈述 try doSomething catch Exception e 但我想要一种方法来知道 doSomething 抛出了哪个异常 在 doSomething 的实现中没有 throw 语句
  • Cucumber Java 与 Spring Boot 集成 - Spring @Autowired 抛出 NullPointer 异常

    我正在为 Spring boot 应用程序编写 cucumber java 单元测试来测试每个功能 当我与 Spring Boot 集成时 Autowired 类抛出 NullPointer 异常 Spring Boot应用程序类 Spri
  • 我可以创建自定义 java.* 包吗?

    我可以创建一个与预定义包同名的自己的包吗在Java中 比如java lang 如果是这样 结果会怎样 这难道不能让我访问该包的受保护的成员 如果不是 是什么阻止我这样做 No java lang被禁止 安全管理器不允许 自定义 类java
  • 游戏内的java.awt.Robot?

    我正在尝试使用下面的代码来模拟击键 当我打开记事本时 它工作正常 但当我打开我想使用它的游戏时 它没有执行任何操作 所以按键似乎不起作用 我尝试模拟鼠标移动和点击 这些动作确实有效 有谁知道如何解决这个问题 我发现这个问题 如何在游戏中使用
  • 具有特定参数的 Spring AOP 切入点

    我需要创建一个我觉得很难描述的方面 所以让我指出一下想法 com x y 包 或任何子包 中的任何方法 一个方法参数是接口 javax portlet PortletRequest 的实现 该方法中可能有更多参数 它们可以是任何顺序 我需要
  • react-native - 图像需要来自 JSON 的本地路径

    你好社区 我正在react native中开发一个测试应用程序 并尝试从本地存储位置获取图像 我实际在做什么 我将图像直接链接源提供给 var 并在渲染函数中调用此方法 react 0 14 8 react native 0 23 1 np
  • 为什么这个作业不起作用?

    我有课Results which extends ArrayList
  • 如何从 Maven 存储库引用本机 DLL?

    如果 JAR 附带 Maven 存储库中的本机 DLL 我需要在 pom xml 中放入什么才能将该 DLL 放入打包中 更具体地举个例子Jacob http search maven org artifactdetails 7Cnet s
  • 调整添加的绘制组件的大小和奇怪的摆动行为

    这个问题困扰了我好几天 我正在制作一个特殊的绘画程序 我制作了一个 JPanel 并添加了使用 Paint 方法绘制的自定义 jComponent 问题是 每当我调整窗口大小时 所有添加的组件都会 消失 或者只是不绘制 因此我最终会得到一个

随机推荐

  • For 语句,每第 1000 次演练,做某事

    我正在遍历 For 循环 100 000 次 这个数字可以多样化 每第一千次我都想做一些特别的事情 那些我在其他演练中没有做的事情 像这样的东西 for int i 0 i lt 100000 i doTasks Normal if i 1
  • git-http-backend 与 apache2.4 Centos 7

    我尝试在我的 apache 服务器上设置 Git 服务器 但它不起作用 我得到了以下 git conf SetEnv GIT PROJECT ROOT var www html git project1 SetEnv GIT HTTP EX
  • Java 8 Stream API 中的多个聚合函数

    我有一个类定义如下 public class TimePeriodCalc private double occupancy private double efficiency private String atDate 我想使用 Java
  • 如何防止在 IE9 中加载页面时出现“无法获取属性‘dir’的值:对象为 null 或未定义”错误

    我有一个 Dojo 1 7 4 应用程序 在 IE9 中加载页面时出现 无法获取属性 dir 的值 对象为 null 或未定义 错误 我使用的是 AMD 版本 当它必须单独加载所有文件时 不会发生错误 我可以控制的所有代码都包含在 dojo
  • Kotlin:抑制未使用的属性?

    我的源代码如下 有警告 从未使用属性 我添加了 Suppress UNUSED PARAMETER Suppress UNUSED PROPERTY GETTER Suppress UNUSED PROPERTY SETTER 然而 它们都
  • 关闭 vba 生成的 Excel 绘图上的标记阴影

    我正在将一些用于在 Excel 中生成散点图的代码从 Win 7 Excel 2010 移植到 OS X Excel 2011 在 Mac 上 数据点显示有阴影 我不想要阴影 也不知道如何摆脱它 Using 这个工作表 http dl dr
  • C++ 指针数组的内存分配

    我有一个关于内存分配的问题 假设我创建了一个像这样的指针数组 int numbers new int 1024 1024 我原以为这需要 8MB 内存 Mac 64 位上为 8 字节指针 但事实并非如此 仅当为每个指针赋值时才分配内存 因此
  • 注册一个全局钩子,检测鼠标是否拖动文件/文本

    我知道有可能为鼠标注册全局钩子 http www codeproject com KB cs globalhook aspx移动 按钮单击 滚动等 但我想知道是否有任何方法可以检测用户是否实际上使用全局挂钩拖动文件或文本 或其他内容 似乎找
  • 从三地址代码到 JVM 字节码的代码生成

    我正在研究 Renjin 的字节码编译器 R 代表 JVM 并尝试将中间三地址码 TAC 表示形式转换为字节码 我查阅过的所有有关编译器的教科书都讨论了代码生成期间的寄存器分配 但我还没有找到任何用于在基于堆栈的虚拟机 如 JVM 上生成代
  • 向 ggplot 添加图例

    这个问题是这篇文章的后续问题 上一篇文章 https stackoverflow com questions 21531230 using geom path from ggplot library 我有12个变量 M1 M2 M12 为此
  • 将位图转换为多边形 - (反向光栅化)[关闭]

    Closed 这个问题是基于意见的 help closed questions 目前不接受答案 给定一个位图图像 上面有一些纯色斑点 您将使用什么算法来构造与斑点形状相同的多边形 这可以通过多个步骤完成 稍后可以通过最佳拟合算法来切割高分辨
  • 如何在 WPF 应用程序中构建动态数据输入表单?

    我正在计划一个 WPF 应用程序 它将 能够创造动态数据输入表格 这意味着表单从数据库中的数据而不是从 XAML 获取要显示的字段及其顺序等 如果可能的话使用 MVVM 模式 我计划这样做 在客户数据输入视图中 我将设置数据上下文
  • 离子应用程序 | Firebase Crashlytics 无法与崩溃报告配合使用?

    我在我们的 Ionic 应用程序中使用 ionic native firebase 插件 并且该插件中包含崩溃报告 由于 Firebase 崩溃报告在 9 月 9 日之后将不再可用 因此我们正在尝试切换到 Firebase Crashlyt
  • 无法使用 C# 将 [] 索引应用于“System.Array”类型的表达式

    我正在尝试使用包含字符串数组的列表 但是当我尝试使用方括号访问数组元素时 我收到错误 我的数组列表声明如下 public List
  • 在 Valgrind 下运行 Eclipse

    这里有人成功运行 Eclipse 吗Valgrind http valgrind org 我正在与涉及 JNI 代码的特别棘手的崩溃作斗争 并希望 Valgrind 或许可以 再次 证明其卓越性 但是当我在 Valgrind 下运行 Ecl
  • nltk 函数计算某些单词的出现次数

    nltk书中有一个问题 使用 state union 语料库阅读器阅读国情咨文演讲的文本 计算每个文档中男性 女性和人物的出现次数 随着时间的推移 这些词的使用发生了什么变化 我想我可以使用像 state union 1945 Truman
  • Selenium WebDriver 中的 DesiredCapability 有什么用?

    Selenium WebDriver 中的 DesiredCapability 有什么用 我们什么时候想使用它以及如何使用 举例回答将不胜感激 您应该阅读有关的文档所需能力 https github com SeleniumHQ selen
  • 终端进程命令无法启动退出代码:0 和退出代码:2

    Visual Studio 代码终端无法工作 捷径ctrl 因为终端不工作 Error The terminal process terminated with exit code 0 终端进程命令 C WINDOWS System32 W
  • t.Cleanup 有什么用?

    问题 我想知道的用例t CleanupGo1 14中引入 与使用 defer 相比 t Cleanup 有何便利 https golang org pkg testing T Cleanup https golang org pkg tes
  • 图像文件的加密与解密

    结合我的另一个question https stackoverflow com questions 12131627 image encryption decryption 并且在更改了这一小部分代码之后 FileOutputStream