java
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;public class RsaUtils {private static String publicKey = "publicKey";private static String = "privateKey";public static void main(String[] args) {String message = "123456";String messageEn = encrypt(message);System.out.println("加密:" + messageEn);String messageDe = decrypt(messageEn);System.out.println("解密:" + messageDe);}public static void genKeyPair() throws NoSuchAlgorithmException {KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");keyPairGen.initialize(1024, new SecureRandom());KeyPair keyPair = keyPairGen.generateKeyPair();RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));System.out.println("公钥:" + publicKeyString);System.out.println("私钥: " + privateKeyString);}public static String encrypt(String str) {try {byte[] decoded = Base64.decodeBase64(publicKey);RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));Cipher cipher = Cipher.getInstance("RSA");cipher.init(Cipher.ENCRYPT_MODE, pubKey);return Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));} catch (Exception e) {return null;}}public static String decrypt(String str) {try {byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));byte[] decoded = Base64.decodeBase64(privateKey);RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));Cipher cipher = Cipher.getInstance("RSA");cipher.init(Cipher.DECRYPT_MODE, priKey);return new String(cipher.doFinal(inputByte));} catch (Exception e) {return null;}}
}
js
<html>
<head></head>
<body>
<script src="./jsencrypt.min.js"></script>
<script>var jsencrypt = new JSEncrypt();jsencrypt.setPublicKey('publicKey');var messageEn =jsencrypt.encrypt('123456');console.log(messageEn);jsencrypt.setPrivateKey('privateKey')var messageDe =jsencrypt.decrypt(messageEn);console.log(messageDe);
</script>
</body>
</html>