Get the App
SLTechnology News&Howtos  ›  Development  › 

How to implement RSA algorithm by Java

Shulou Source: shulou.com Published: 2022-06-02 12:48:28 09月18日 Update

Editor to share with you Java how to achieve RSA algorithm, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to understand it!

The following is a reference clip:

Package rsa

Import java.math.BigInteger

Public class RSA {

Private long p,q,e,d,n

Public RSA () {

Int pIndex = (int) (Math.random () * 10)

Int qIndex

Int eIndex

Do {

QIndex = (int) (Math.random () * 10)

}

While (qIndex==pIndex)

Do {

EIndex = (int) (Math.random () * 10)

}

While (eIndex==pIndex | | eIndex==pIndex)

P = 1033

Q = 2017

E = 29437

N = puniq

D = calculateD ()

}

Private long calculateD () {

Long t0 = 0, T1 = 1, T2 =-1

Long R0 = (pmae1) * (qmer1), m = r0Magi R1 = e, R2 =-1

Do {

Long Q = r0/r1

R2 = r0-r1*q

If (R2 benchmark 0) break

T2 = t0-T1 / Q

While (t2pragm) {

T2% = m

}

R0 = R1

R1 = R2

T0 = T1

T1 = T2

} while (R2 cycles 0)

If (r1room1) {

Return 0

}

Else {

Return t2

}

}

Public long getE () {

Return e

}

Public long getN () {

Return n

}

Public long getD () {

Return d

}

Public BigInteger encode (BigInteger data) {

Return pow (data,d) .mod (new BigInteger (n + ""))

}

Public BigInteger decode (BigInteger code) {

Return pow (code,e) .mod (new BigInteger (n + ""))

}

Public BigInteger pow (BigInteger data,long p) {

Data = data.pow ((int) p)

Return data

}

Public static void main (String args []) {

RSA rsa = new RSA ()

BigInteger data = new BigInteger ("222222")

Long oldtime = System.currentTimeMillis ()

BigInteger code = rsa.encode (data)

Long newtime = System.currentTimeMillis ()

Double codetime = (double) (newtime-oldtime) / 1000

Oldtime = System.currentTimeMillis ()

BigInteger decode = rsa.decode (code)

Newtime = System.currentTimeMillis ()

Double decodetime = (double) (newtime-oldtime) / 1000

System.out.println ("privateKey:" + rsa.d)

System.out.println ("publickKey:" + rsa.e)

System.out.println ("N:" + rsa.n)

System.out.println ("data:" + data)

System.out.println ("code:" + code+ "time:" + codetime)

System.out.println ("decode:" + decode+ "time:" + decodetime)

}

} these are all the contents of the article "how to implement the RSA algorithm in Java". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: Articles algorithms content not so much most more fragments knowledge industry information information channels channels references learning help Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Apple Linux Shulou Information macOS