Current location - Quotes Website - Personality signature - How to realize rsa encryption and decryption with javascript
How to realize rsa encryption and decryption with javascript
The specific realization idea is as follows:

1。 The server generates public and private keys and saves them.

2。 After the client requests to log in to the page, it will randomly generate a string.

3。 Then this random string is used as a key encryption password, and then the generated random string is encrypted with the public key obtained from the server.

4。 These two ciphertexts are transmitted to the server, and the server decrypts the random string with the private key, and then decrypts the encrypted ciphertext with this private key.

One of the keys is to find the public key of the server, which is transmitted to the client. After the client encrypts the string with this public key, it can be solved with the private key on the server side.

This paper is to achieve this step.

The encryption algorithm is RSA:

1。 RSA on the server? Java implementation.

/**?

*?

*/?

Parcel? com . sun soft . struts . util; ?

Import? Java . io . bytearrayoutputstream; ?

Import? Java . io . file inputstream; ?

Import? Java . io . file output stream; ?

Import? Java . io . objectinputstream; ?

Import? Java . io . object output stream; ?

Import? Java . math . big integer; ?

Import? Java . security . key factory; ?

Import? Java . security . key pair; ?

Import? Java . security . key pair generator; ?

Import? Java . security . nosuchalgorithm exception; ?

Import? Java . security . private key; ?

Import? Java . security . public key; ?

Import? Java . security . securerandom; ?

Import? Java . security . interfaces . rsaprivatekey; ?

Import? Java . security . interfaces . RSA public key; ?

Import? Java . security . spec . invalidkeyspecexception; ?

Import? Java . security . spec . rsaprivatekeyspec; ?

Import? Java . security . spec . rsapapublickeyspec; ?

Import? javax . crypto . cipher; ?

/**?

*? RSA? Tool class. Provide peer-to-peer encryption, decryption and key generation methods. ?

*? You need to download bcprov-JDK14-123.jar in http://www.bouncycastle.org. ?

*?

*/?

Public? Class? RSAUtil? {?

/**?

*? *? Generate key pairs? *?

*?

*? @ Return? KeyPair? *?

*? @throws? Encryption exception?

*/?

Public? Static electricity KeyPair? generateKeyPair()? Throwing? Exceptions? {?

Try it? {?

KeyPairGenerator? keyPairGen? =? keypairgenerator . getinstance(" RSA ",

New? org . bouncy castle . JCE . provider . bouncy castle provider()); ?

Final? int? KEY_SIZE? =? 1024; //? There is nothing to say. This value is related to the size of block encryption, and can be changed, but it cannot be too large, otherwise it will be inefficient?

keyPairGen.initialize(KEY_SIZE,? New? SecureRandom()); ?

KeyPair? keyPair? =? keypairgen . generatekeypair(); ?

SaveKeyPair; ?

Return? Key pair; ?

}? Catch? (exception? e)? {?

Throw? New? Exception (e.getmessage ()); ?

}?

}?

Public? Static electricity KeyPair? GetKeyPair () throws? Abnormal {?

FileInputStream? fis? =? New? file inputstream(" C:/RSA key . txt "); ?

ObjectInputStream? oos? =? New? ObjectInputStream(fis); ?

KeyPair? kp=? (KeyPair)? OOS . read object(); ?

OOS . close(); ?

fis . close(); ?

Return? KP; ?

}?

Public? Static electricity Invalid? saveKeyPair(KeyPair? Kp) vote? Abnormal {?

FileOutputStream? fos? =? New? file output stream(" C:/RSA key . txt "); ?

ObjectOutputStream? oos? =? New? ObjectOutputStream(fos); ?

//Generate a key?

OOS . writeobject(KP); ?

OOS . close(); ?

fos . close(); ?

}?

/**?

*? *? Generate public key? *?

*?

*? @param? Modulus *?

*? @param? publicExponent? *?

*? @ Return? RSAPublicKey? *?

*? @throws? Exceptions?

*/?

Public? Static electricity RSAPublicKey? generateRSAPublicKey(byte[]? Modulus,?

byte[]? publicExponent)? Throwing? Exceptions? {?

KeyFactory? keyFac? =? null?

Try it? {?

keyFac? =? KeyFactory.getInstance("RSA ",

New? org . bouncy castle . JCE . provider . bouncy castle provider()); ?

}? Catch? (NoSuchAlgorithmException? ex)? {?

Throw? New? Exception (ex.getmessage ()); ?

}?

RSAPublicKeySpec? pubKeySpec? =? New? RSAPublicKeySpec (new? BigInteger(?

Modulus), New? big integer(public index)); ?

Try it? {?

Return? (RSAPublicKey)? keyfac . generate public(pubkey spec); ?

}? Catch? (InvalidKeySpecException? ex)? {?

Throw? New? Exception (ex.getmessage ()); ?

}?

}?

/**?

*? *? Generate private key? *?

*?

*? @param? Modulus *?

*? @param? privateExponent? *?

*? @ Return? RSAPrivateKey? *?

*? @throws? Exceptions?

*/?

Public? Static electricity RSAPrivateKey? generateRSAPrivateKey(byte[]? Modulus,?

byte[]? privateExponent)? Throwing? Exceptions? {?

KeyFactory? keyFac? =? null?

Try it? {?

keyFac? =? KeyFactory.getInstance("RSA ",

New? org . bouncy castle . JCE . provider . bouncy castle provider()); ?

}? Catch? (NoSuchAlgorithmException? ex)? {?

Throw? New? Exception (ex.getmessage ()); ?

}?

RSAPrivateKeySpec? priKeySpec? =? New? RSAPrivateKeySpec (new? BigInteger(?

Modulus), New? big integer(private index)); ?

Try it? {?

Return? (RSAPrivateKey)? key fac . generate private(prikey spec); ?

}? Catch? (InvalidKeySpecException? ex)? {?

Throw? New? Exception (ex.getmessage ()); ?

}?

}?

/**?

*? *? Encryption? *?

*?

*? @param? Keys?

* encryption key? *?

*? @param? Data?

* plaintext data to be encrypted? *?

*? @ Return? Encrypted data? *?

*? @throws? Exceptions?

*/?

Public? Static electricity byte[]? Encryption (PublicKey? pk,? byte[]? Data)? Throwing? Exceptions? {?

Try it? {?

Password? Password? =? Cipher.getInstance("RSA ",

New? org . bouncy castle . JCE . provider . bouncy castle provider()); ?

Cipher.init (password. Encryption mode? PK); ?

int? blockSize? =? cipher . get blocksize(); //? Get the encrypted block size, for example, the data before encryption is 128 byte, key_size= 1024?

//? The encryption block size is 127?

//? Byte, which is 128 bytes after encryption; So * * * has two encrypted blocks. The first one is 127?

//? The second byte is 1 byte?

int? outputSize? =? cipher . getoutputsize(data . length); //? Get the encrypted block size after encryption?

int? leavedSize? =? Data length? %? blockSize?

int? blocksSize? =? leavedSize? ! =? 0 data length? /? blockSize? +? 1?

:? Data length? /? blockSize?

byte[]? Raw? =? New? byte[outputSize? *? blocksSize]; ?

int? Me? =? 0; ?

What time? (Data. Length? -? Me? *? blockSize? & gt? 0)? {?

What if? (Data. Length? -? Me? *? blockSize? & gt? blockSize)?

cipher.doFinal(data,? Me? *? Block size,? Block size,? Raw? Me?

*? output size); ?

Or what?

cipher.doFinal(data,? Me? *? Block size,? Data length? -? Me?

*? Block size,? Raw? Me? *? output size); ?

//? The doUpdate method is not available here. After checking the source code, I found that there was no actual action except putting byte[] in it after each doUpdate.

//? ByteArrayOutputStream, and all bytes [] [] are encrypted at the end of doFinal, but the encryption block size is likely to have exceeded?

//? OutputSize, so we must use the dofinal method. ?

i++; ?

}?

Return? Raw; ?

}? Catch? (exception? e)? {?

Throw? New? Exception (e.getmessage ()); ?

}?

}?

/**?

*? *? Decryption? *?

*?

*? @param? Keys?

* Decryption key? *?

*? @param? Raw?

* Encrypted data? *?

*? @ Return? Decrypt plaintext? *?

*? @throws? Exceptions?

*/?

Public? Static electricity byte[]? Decryption (PrivateKey? pk,? byte[]? raw)? Throwing? Exceptions? {?

Try it? {?

Password? Password? =? Cipher.getInstance("RSA ",

New? org . bouncy castle . JCE . provider . bouncy castle provider()); ?

Cipher.init (password. Decryption mode? PK); ?

int? blockSize? =? cipher . get blocksize(); ?

ByteArrayOutputStream? Bout? =? New? ByteArrayOutputStream(64); ?

int? j? =? 0; ?

What time? (raw. length? -? j? *? blockSize? & gt? 0)? {?

bout.write(cipher.doFinal(raw,j? *? Block size,? block size)); ?

j++; ?

}?

Return? bout . tobytearray(); ?

}? Catch? (exception? e)? {?

Throw? New? Exception (e.getmessage ()); ?

}?

}?

/**?

*? *? *?

*?

*? @param? args? *?

*? @throws? Exceptions?

*/?

Public? Static electricity Invalid? main(String[]? args)? Throwing? Exceptions? {?

RSAPublicKey? rsap? =? (RSAPublicKey)? RSAUtil.generateKeyPair()。 getPublic(); ?

String? Testing? =? "hello? The world "; ?

byte[]? en_test? =? encrypt(getKeyPair()。 getPublic()、test . getbytes()); ?

byte[]? de_test? =? Decryption (getKeyPair ()). getPrivate(),en _ test); ?

System.out.println (new? string(de _ test)); ?

}?

} 2. Test page:

IndexAction.java