[英]How to generate private public key in JAVA using no external libraries
We have been given an assignment part of which requires us to generate a public private key pair.我们得到了一项任务,其中要求我们生成一对公私钥。 These do not need to be particularly secure, as it is just for demonstration of the concept.
这些不需要特别安全,因为它只是为了概念的演示。
We can not use any sort of cryptography libraries or external tools.我们不能使用任何类型的密码学库或外部工具。
How would I go about generating these?我将如何生成这些 go?
Edit: Found a pretty nice explanation of RSA here: https://www.educative.io/edpresso/what-is-the-rsa-algorithm编辑:在这里找到了 RSA 的一个很好的解释: https://www.educative.io/edpresso/what-is-the-rsa-algorithm
I use JShell to demonstrate the basic public-private key generation just using Java's BigInteger
:我使用 JShell 来演示仅使用 Java 的
BigInteger
的基本公私密钥生成:
jshell> import java.math.BigInteger;
jshell> var rnd = new java.security.SecureRandom();
rnd ==> Hash_DRBG,SHA-256,128,reseed_only
First we need 2 primes首先我们需要2个素数
jshell> var p1 = BigInteger.probablePrime(512, rnd);
p1 ==> 1176110601168217581401499298469596353224364190716 ... 72507270343325790065694831
jshell> var p2 = BigInteger.probablePrime(512, rnd);
p2 ==> 1001341560055006431459083188828513502474297271020 ... 34378293673605844490263567
Next we calculate the public key.接下来我们计算公钥。 0x10001 is a common exponent for the public key.
0x10001 是公钥的公共指数。
jshell> var n = p1.multiply(p2);
n ==> 1177688424171014462551464978852125044384293220079 ... 24824881562893076179522177
jshell> var e = BigInteger.valueOf(0x10001);
e ==> 65537
The public key is e
and n
.公钥是
e
和n
。 Now the private part.现在是私人部分。
jshell> var phi = p1.subtract(BigInteger.ONE).multiply(p2.subtract(BigInteger.ONE));
phi ==> 1177688424171014462551464978852125044384293220079 ... 17939317545961441623563780
jshell> var d = e.modInverse(phi);
d ==> 7023685818262702180949167670691999860354377649273 ... 38390163809778429090416313
The private key is now d
and n
.私钥现在是
d
和n
。
Let's test it:让我们测试一下:
jshell> var secret = BigInteger.valueOf(1337);
secret ==> 1337
jshell> var enc = secret.modPow(e, n);
enc ==> 1059982071031392497566614763259148320406936402012 ... 39171914529632475117049800
jshell> enc.modPow(d, n);
$11 ==> 1337
We could send enc
over the wire, and nobody could decrypt it without the knowledge of the private key.我们可以通过网络发送
enc
,没有人可以在不知道私钥的情况下解密它。 Well, at least in theory.好吧,至少在理论上是这样。 In practice, you should pad your messages.
实际上,您应该填充消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.