选择Java加密算法第3部分–公钥/私钥非对称加密

抽象

这是涵盖Java加密算法的三部分博客系列的第3部分。 本系列介绍如何实现以下目标:

  1. 使用SHA–512散列
  2. 使用AES–256的单密钥对称加密
  3. RSA–4096

这第三篇文章详细介绍了如何实现非对称的RSA-4096公/私钥加密。 让我们开始吧。

免责声明

这篇文章仅供参考。 在使用所提供的任何信息之前,请认真思考。 从中学到东西,但最终自己做出决定,风险自负。

要求

我使用以下主要技术完成了本文的所有工作。 您可能可以使用不同的技术或版本来做相同的事情,但不能保证。

  • Java 1.8.0_152_x64
  • NetBeans 8.2(内部版本201609300101)
  • Maven 3.0.5(与NetBeans捆绑在一起)

下载

访问我的GitHub页面以查看我所有的开源项目。 这篇文章的代码位于项目中: thoth-cryptography

非对称加密

关于

非对称算法基于两个密钥:公钥和私钥。 公钥负责加密,私钥负责解密。 公用密钥可以自由分发。 使用公共密钥,任何客户端都可以加密一条消息,只有您(使用私有密钥)可以解密该消息(非对称算法,第3段)。

非对称算法是Internet的主力军。 像SSH,OpenPGP,SSL和TLS之类的协议依赖于非对称算法(Rouse,2016,第2段)。 使用网络浏览器进行在线银行之类的工作的人都固有地知道非对称算法的重要性。

截至目前,已完成的研究似乎表明,以下是最佳和最安全的公钥/私钥,非对称加密算法(Sheth,2017年,“选择正确的算法”,第2段):

  1. 算法: RSA
  2. 模式: ECB //确实没有,但是需要ECB才能使Java工作。
  3. 填充: OAEPWithSHA–512AndMGF1Padding
  4. 密钥大小: 4096位

RSA不是分组密码,因此ECB模式没有多大意义,但是,即使未在内部使用该模式,也需要ECB来使Java工作(Brightwell,2015年)。 OAEP提供了高度的随机性和填充性。 让我们看一个例子。

清单1是RsaTest.java单元测试。 这是以下内容的完整演示:

  1. 生成并存储RSA 4096位密钥
  2. RSA加密
  3. RSA解密

清单2显示了RsaKeyPairProducer.java 。 这是一个帮助程序类,负责产生一个新的KeyPairKeyPair对同时包含PublicKeyPrivateKey
清单3显示了RsaPrivateKeyProducer.java 。 这是一个帮助程序类,负责从byte[]再现PrivateKey

清单4显示了RsaPublicKeyProducer.java 。 这是一个帮助程序类,负责从byte[]复制PublicKey

清单5显示了ByteArrayWriter.java ,清单6显示了ByteArrayReader.java 。 这些是帮助程序类,负责将byte[]读写到文件中。 由您决定如何存储密钥的byte[] ,但需要将其安全地存储在某个地方(文件,数据库,git存储库等)。

清单7显示了RsaEncrypter.java 。 这是一个负责加密的助手类。

最后,清单8显示了RsaDecrypter.java 。 这是一个负责解密的助手类。

清单1 – RsaTest.java类

package org.thoth.crypto.asymmetric;import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.thoth.crypto.io.ByteArrayReader;
import org.thoth.crypto.io.ByteArrayWriter;/**** @author Michael Remijan mjremijan@yahoo.com @mjremijan*/
public class RsaTest {static Path privateKeyFile;static Path publicKeyFile;@BeforeClasspublic static void beforeClass() throws Exception {// Store the PrivateKey and PublicKey bytes in the ./target// diretory. Do this so it will be ignore by source control.// We don't want this file committed.privateKeyFile= Paths.get("./target/RsaPrivate.key").toAbsolutePath();publicKeyFile= Paths.get("./target/RsaPublic.key").toAbsolutePath();// Create KeyPair for RSAKeyPair keyPair= new RsaKeyPairProducer().produce();// Store the PrivateKey bytes. This is what// you want to keep absolutely safe{ByteArrayWriter writer = new ByteArrayWriter(privateKeyFile);writer.write(keyPair.getPrivate().getEncoded());}// Store the PublicKey bytes.  This you// can freely distribute so others can// encrypt messages which you can then// decrypt with the PrivateKey you keep safe.{ByteArrayWriter writer = new ByteArrayWriter(publicKeyFile);writer.write(keyPair.getPublic().getEncoded());}}@Testpublic void encrypt_and_decrypt() throws Exception {// setupPrivateKey privateKey= new RsaPrivateKeyProducer().produce(new ByteArrayReader(privateKeyFile).read());PublicKey publicKey= new RsaPublicKeyProducer().produce(new ByteArrayReader(publicKeyFile).read());RsaDecrypter decrypter= new RsaDecrypter(privateKey);RsaEncrypter encrypter= new RsaEncrypter(publicKey);String toEncrypt= "encrypt me";// runbyte[] encryptedBytes= encrypter.encrypt(toEncrypt);System.out.printf("Encrypted %s%n", new String(encryptedBytes,"UTF-8"));String decrypted= decrypter.decrypt(encryptedBytes);// assertAssert.assertEquals(toEncrypt, decrypted);}}

清单2 – RsaKeyPairProducer.java类

package org.thoth.crypto.asymmetric;import java.security.KeyPair;
import java.security.KeyPairGenerator;/**** @author Michael Remijan mjremijan@yahoo.com @mjremijan*/
public class RsaKeyPairProducer {/*** Generates a new RSA-4096 bit {@code KeyPair}.** @return {@code KeyPair}, never null* @throws RuntimeException All exceptions are caught* and re-thrown as {@code RuntimeException}*/public KeyPair produce() {KeyPairGenerator keyGen;try {keyGen = KeyPairGenerator.getInstance("RSA");//keyGen.initialize(3072);keyGen.initialize(4096);return keyGen.generateKeyPair();} catch (Exception ex) {throw new RuntimeException(ex);}}
}

清单3 – RsaPrivateKeyProducer.java类

package org.thoth.crypto.asymmetric;import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;/**** @author Michael Remijan mjremijan@yahoo.com @mjremijan*/
public class RsaPrivateKeyProducer {/*** Regenerates a previous RSA {@code PrivateKey}.** @param encodedByteArrayForPrivateKey The bytes this method* will use to regenerate a previously created {@code PrivateKey}** @return {@code PrivateKey}, never null* @throws RuntimeException All exceptions are caught* and re-thrown as {@code RuntimeException}*/public PrivateKey produce(byte[] encodedByteArrayForPrivateKey) {try {PrivateKey privateKey = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(encodedByteArrayForPrivateKey));return privateKey;} catch (Exception ex) {throw new RuntimeException(ex);}}
}

清单4 – RsaPublicKeyProducer.java类

package org.thoth.crypto.asymmetric;import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;/**** @author Michael Remijan mjremijan@yahoo.com @mjremijan*/
public class RsaPublicKeyProducer {/*** Regenerates a previous RSA {@code PublicKey}.** @param encodedByteArrayForPublicKey The bytes this method* will use to regenerate a previously created {@code PublicKey}** @return {@code PublicKey}, never null* @throws RuntimeException All exceptions are caught* and re-thrown as {@code RuntimeException}*/public PublicKey produce(byte[] encodedByteArrayForPublicKey) {try {PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(encodedByteArrayForPublicKey));return publicKey;} catch (Exception ex) {throw new RuntimeException(ex);}}
}

清单5 – ByteArrayWriter.java类

package org.thoth.crypto.io;import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;/**** @author Michael Remijan mjremijan@yahoo.com @mjremijan*/
public class ByteArrayWriter {protected Path outputFile;private void initOutputFile(Path outputFile) {this.outputFile = outputFile;}private void initOutputDirectory() {Path outputDirectory = outputFile.getParent();if (!Files.exists(outputDirectory)) {try {Files.createDirectories(outputDirectory);} catch (IOException e) {throw new RuntimeException(e);}}}public ByteArrayWriter(Path outputFile) {initOutputFile(outputFile);initOutputDirectory();}public void write(byte[] bytesArrayToWrite) {try (OutputStream os= Files.newOutputStream(outputFile);PrintWriter writer=  new PrintWriter(os);){for (int i=0; i<bytesArrayToWrite.length; i++) {if (i>0) {writer.println();}writer.print(bytesArrayToWrite[i]);}} catch (IOException ex) {throw new RuntimeException(ex);}}
}

清单6 – ByteArrayReader.java类

package org.thoth.crypto.io;import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Scanner;/**** @author Michael Remijan mjremijan@yahoo.com @mjremijan*/
public class ByteArrayReader {protected Path inputFile;public ByteArrayReader(Path inputFile) {this.inputFile = inputFile;}public byte[] read() {try (Scanner scanner=  new Scanner(inputFile);ByteArrayOutputStream baos= new ByteArrayOutputStream();){while (scanner.hasNext()) {baos.write(Byte.parseByte(scanner.nextLine()));}baos.flush();return baos.toByteArray();} catch (IOException ex) {throw new RuntimeException(ex);}}
}

清单7 – RsaEncrypter.java类

package org.thoth.crypto.asymmetric;import java.security.PublicKey;
import javax.crypto.Cipher;/**** @author Michael Remijan mjremijan@yahoo.com @mjremijan*/
public class RsaEncrypter {protected RsaCipher cipher;public RsaEncrypter(PublicKey key) {this.cipher = new RsaCipher(Cipher.ENCRYPT_MODE, key);}public byte[] encrypt(String message) {try {return cipher.update(message.getBytes("UTF-8")).doFinal();} catch (Exception e) {throw new RuntimeException(e);}}
}

清单8 – RsaDecrypter.java类

package org.thoth.crypto.asymmetric;import java.security.PrivateKey;
import javax.crypto.Cipher;/**** @author Michael Remijan mjremijan@yahoo.com @mjremijan*/
public class RsaDecrypter {protected RsaCipher cipher;public RsaDecrypter(PrivateKey key) {this.cipher = new RsaCipher(Cipher.DECRYPT_MODE, key);}public String decrypt(byte[] message) {try {return new String(cipher.update(message).doFinal(), "UTF-8");} catch (Exception e) {throw new RuntimeException(e);}}}

摘要

加密并不容易。 简单的示例将为您的应用程序带来带有安全漏洞的实现。 如果需要公用/专用密钥,非对称加密算法,请使用具有4096位密钥的RSA / ECB / OAEPWithSHA–512AndMGF1Padding。

参考文献

Sheth,M.(2017年4月18日)。 Java密码学中的加密和解密。 从https://www.veracode.com/blog/research/encryption-and-decryption-java-cryptography检索。

  • 最佳算法,模式和填充
  • 使用4096位密钥

华盛顿州布莱特韦尔,雨披。 (2015年5月4日)。 ECB模式与RSA加密一起使用是否安全? 从https://crypto.stackexchange.com/questions/25420/is-ecb-mode-safe-to-use-with-rsa-encryption检索。

  • 欧洲央行不适用; Java不会在幕后使用它。
  • RSA使用随机性和填充来避免相同明文的ECB问题生成相同的密文

玛丽莲娜 (2016年11月29日)。 Java –非对称密码术示例。 从https://www.mkyong.com/java/java-asymmetric-cryptography-example/检索。

  • 将公用/专用密钥写入文件
  • 从文件中读取公钥/私钥
  • 加密与解密

密钥大小。 (2017年10月12日)。 维基百科。 取自https://en.wikipedia.org/wiki/Key_size 。

  • 到2030年,2048位密钥就足够了
  • 如果2030年以后仍需要安全性,则应使用3072位的RSA密钥长度

用户4982。 (2013年11月4日)。 IV如何与RSA加密关联使用? 取自https://crypto.stackexchange.com/questions/11403/how-are-ivs-used-in-association-with-rsa-encryption 。

  • IV值不适用于RSA

翻译自: https://www.javacodegeeks.com/2017/12/choosing-java-cryptographic-algorithms-part-3-public-private-key-asymmetric-encryption.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/349582.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Error: Cannot find module '@babel/core'

官方默认babel-loader需要搭配最新版本babel 更新到最高版本: npm install -D babel-loader babel/core babel/preset-env webpack 转载于:https://www.cnblogs.com/nocry/p/11493363.html

javabeans_膨胀的JavaBeans –不要在您的API中添加“ Getters”

javabeans我已经最近在博客的想法的JavaBeans™如何可以扩展以减少在Java世界中&#xff0c;这被广泛接受的公约设立的膨胀。 该文章在DZone上重新发布&#xff0c;并在这里获得了颇具争议的反馈&#xff08;例如&#xff0c;大多数试图将一些新想法带入Java世界的想法&#xf…

uniapp 子组件 props拿不到数据_来吧!一文彻底搞定Vue组件!

点击蓝色 “达达前端小酒馆” 关注我哦!加个 “星标” &#xff0c;每天一篇文章&#xff0c;一起学编程作者 | Jeskson来源 | 达达前端小酒馆Vue组件的概述组件是什么呢&#xff0c;了解组件对象的分析&#xff0c;Vue组件中的data属性&#xff0c;props传递数据的原理到底是…

csp-s模拟测试41「夜莺与玫瑰·玫瑰花精·影子」

夜莺与玫瑰 题解 联赛$T1$莫比乌斯$\%\%\%$ $dead$ $line$是直线 首先横竖就是$nm$这比较显然 枚举方向向量 首先我们枚举方向向量时只枚举右下方向,显然贡献$*2$就是所有斜着的直线 $i,j$表示当自己向右$i$个单位长度,向下$j$单位长度 我们相同斜率下只算最短的线贡献,(因为其…

春天重试,因为冬天来了

好的&#xff0c;这实际上与冬天无关&#xff0c;众所周知&#xff0c;冬天已经到了 。 它是关于Spring Retry的&#xff0c;Spring是一个小的Spring框架库&#xff0c;它使我们可以将重试功能添加到应可重试的任何任务中。 这里有一个很好的教程 &#xff0c;解释了如何设置简…

python做些什么项目_Python 的练手项目有哪些值得推荐

1 Web方向的练手项目 这个其实是肯定不用多少的了。Python的练手项目就是可以做一个网站了。我们可以做一个属于自己的博客。在做博客的时候&#xff0c;我们可以巩固的知识点是 HtmlCSSJS的基础知识&#xff0c;以及熟练的运用Python的Web开发框架&#xff08;例如Django或者F…

删除某个时间段之前的文件

/* * 删除文件夹下$n分钟前创建的文件 * param $dir 要处理的目录&#xff0c;物理路径&#xff0c;结尾不加\ * param $n 过期时间&#xff0c;单位为分钟 * return void */function z_del_file_by_ctime($dir,$n){ if(is_dir($dir)){ if($dhopendir($dir)){ …

技术管理规划-路径跟资源

背景 评估团队的投入和产出或者给上级做汇报&#xff0c;都需要弄清楚需要投入多少资源&#xff0c;而资源主要跟两个因素息息相关&#xff0c;即团队目标&#xff0c;此外还有路径和手段&#xff1b; 增加人力前的三个问题&#xff1f; 1.资源的丰富性&#xff1f; 人&#xf…

python保存代码_python入门(5)使用文件编辑器编写代码并保存执行

原博文 2017-04-21 17:21 − python入门&#xff08;5&#xff09;使用文件编辑器编写代码并保存执行 两款文本编辑器&#xff1a; 一个是Sublime Text&#xff0c;免费使用&#xff0c;但是不付费会弹出提示框&#xff1a; 一个是Notepad&#xff0c;免费使用&#xff0c;有中…

lucene索引搜索_Lucene –快速添加索引和搜索功能

lucene索引搜索什么是Lucene&#xff1f; Apache LuceneTM是完全用Java编写的高性能&#xff0c;功能齐全的文本搜索引擎库。 它是一项适用于几乎所有需要全文本搜索的应用程序的技术&#xff0c;尤其是跨平台。 Lucene可以纯文本&#xff0c;整数&#xff0c;索引PDF&#xf…

从graphql endpoint获取schema文件

graphql server端有更新&#xff0c;client端需要重新获取schema文件用于创建新的api request&#xff0c;下面简要记录如何从graphql endpoint获取schema文件 You can simply install the CLI using npm or yarn by running the following command. This will add the graphql…

pythonclass全局变量_python的局部变量,全局变量,类变量,实例变量

定义&#xff1a; a、全局变量&#xff1a;在模块内、在所有函数外面、在class外面&#xff0c;这就是全局变量。 b、局部变量&#xff1a;在函数内、在class的方法内&#xff08;未加self修饰的&#xff09;&#xff0c;这就是局部变量。 c、 静态变量&#xff1a;在class内的…

使用JUnit 5测试异常

JUnit 5带来了令人敬畏的改进&#xff0c;它与以前的版本有很大的不同。 JUnit 5在运行时需要Java 8&#xff0c;因此Lambda表达式可以在测试中使用&#xff0c;尤其是在断言中。 这些断言之一非常适合测试异常。 设置项目 为了演示JUnit 5的用法&#xff0c;我使用了我的长期…

pytorch list转tensor_点赞收藏:PyTorch常用代码段整理合集

机器之心转载来源&#xff1a;知乎作者&#xff1a;张皓众所周知&#xff0c;程序猿在写代码时通常会在网上搜索大量资料&#xff0c;其中大部分是代码段。然而&#xff0c;这项工作常常令人心累身疲&#xff0c;耗费大量时间。所以&#xff0c;今天小编转载了知乎上的一篇文章…

csp-s模拟测试42「世界线·时间机器·密码」

$t3$不会 世界线 题解 题目让求的就是每个点能到点的数量$-$出度 设每个点能到的点为$f[x]$ 则$f[x]x \sum\limits_{y}^{y\in son[x]} U f[y]$ 用$bitset$优化一下即可,但单纯这样会炸内存,随意$yy$一下,时间换空间,像平衡树一样开个垃圾桶都行 代码 #include<bits/stdc.h&g…

python中的命名空间_深入理解Python中的命名空间和范围

Python中的命名空间和范围 在Python中&#xff0c;每个包、模块、类、函数和方法函数都拥有一个“名称空间”&#xff0c;其中解析了变量名称。下面本篇文章就来带大家认识一下Python中的命名空间和范围&#xff0c;希望对大家有所帮助。什么是命名空间&#xff1a; 命名空间是…

ubuntu16.04安装MATLAB R2017b步骤详解(附完整破解文件包)

https://blog.csdn.net/qq_32892383/article/details/79670871 转载于:https://www.cnblogs.com/BambooEatPanda/p/11523727.html

lisp将图元追加选择_汕尾幸运儿喜爱大乐透 两次买彩票就擒获8注追加二等奖254万元...

6月26日&#xff0c;中国体育彩票大乐透第19073期开奖&#xff0c;前区开出号码04﹑11﹑19﹑20﹑24&#xff0c;后区开出号码08﹑11。当期送出头奖2注&#xff0c;二等奖176注&#xff0c;其中汕尾一位幸运儿陈先生(化名)擒得追加二等奖8注&#xff0c;喜获奖金2541434元。两次…

什么是JAX-RS注释? (第3部分)

JAX-RS注释概述&#xff08;第3部分&#xff09; 这是一个由三部分组成的系列&#xff0c;介绍了用于实现REST端点的注释。 在JAX-RS批注的第二部分中&#xff0c;您了解了&#xff1a; Path注释和PathParam QueryParamter批注 Produces批注 Consumes批注 在这一部分中&a…

csp-c模拟测试43「A·B·C」

B 题解 $f[i][(gcd(prime[j]*prime[k]\%P,P))]\sum\limits_{k1}^{k<num} f[i-1][k]*phi(\frac{P}{prime[j]})$ 关于$phi(\frac{P}{prime[j]})$理解 $phi(\frac{P}{prime[j]})$是求$prime[j]$代表的数的个数 $Pk_0*prime[j]$ $x_1k_1*prime[j]$ $x_2k_2*prime[j]$ ....... 要…