package com.zjjhy.controller.api;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.math.BigInteger;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
public class EncryptionAndDecryption {
public static final String KEY_ALGORITHM = "RSA";
private static final String PUBLIC_KEY = "RSAPublicKey";
private static final String PRIVATE_KEY = "RSAPrivateKey";
public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
private static final int MAX_ENCRYPT_BLOCK = 117;
private static final int MAX_DECRYPT_BLOCK = 128;
public String getPublicKeyStr(Map<String, Object> keyMap) throws Exception {
Key key = (Key) keyMap.get(PUBLIC_KEY);
return encryptBASE64(key.getEncoded());
}
public String getPrivateKeyStr(Map<String, Object> keyMap) throws Exception {
Key key = (Key) keyMap.get(PRIVATE_KEY);
return encryptBASE64(key.getEncoded());
}
public PublicKey getPublicKey(String key) throws Exception {
byte[] keyBytes;
keyBytes = (new BASE64Decoder()).decodeBuffer(key);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PublicKey publicKey = keyFactory.generatePublic(keySpec);
return publicKey;
}
public PrivateKey getPrivateKey(String key) throws Exception {
byte[] keyBytes;
keyBytes = (new BASE64Decoder()).decodeBuffer(key);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
return privateKey;
}
public byte[] decryptBASE64(String key) throws Exception {
return (new BASE64Decoder()).decodeBuffer(key);
}
public String encryptBASE64(byte[] key) throws Exception {
return (new BASE64Encoder()).encodeBuffer(key);
}
public Map<String, Object> initKey() throws Exception {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
keyPairGen.initialize(1024);
KeyPair keyPair = keyPairGen.generateKeyPair();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
Map<String, Object> keyMap = new HashMap<String, Object>(2);
keyMap.put(PUBLIC_KEY, publicKey);
keyMap.put(PRIVATE_KEY, privateKey);
return keyMap;
}
public byte[] sign(byte[] data, String privateKeyStr) throws Exception {
PrivateKey priK = getPrivateKey(privateKeyStr);
Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM);
sig.initSign(priK);
sig.update(data);
return sig.sign();
}
public boolean verify(byte[] data, byte[] sign, String publicKeyStr) throws Exception {
PublicKey pubK = getPublicKey(publicKeyStr);
Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM);
sig.initVerify(pubK);
sig.update(data);
return sig.verify(sign);
}
public byte[] encrypt(byte[] plainText, String publicKeyStr) throws Exception {
PublicKey publicKey = getPublicKey(publicKeyStr);
Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
int inputLen = plainText.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
int i = 0;
byte[] cache;
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(plainText, offSet, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(plainText, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptText = out.toByteArray();
out.close();
return encryptText;
}
public byte[] decrypt(byte[] encryptText, String privateKeyStr) throws Exception {
PrivateKey privateKey = getPrivateKey(privateKeyStr);
Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
int inputLen = encryptText.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(encryptText, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(encryptText, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_DECRYPT_BLOCK;
}
byte[] plainText = out.toByteArray();
out.close();
return plainText;
}
}
package com.zjjhy.controller.api;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
@Controller
@RequestMapping("api/tools")
public class ToolsController extends AbstractApiController {
@Autowired
ToolsService toolsService;
Key key=new Key();
EncryptionAndDecryption mncr=new EncryptionAndDecryption();
@ResponseBody
@RequestMapping(value = "/ciphertext", method = RequestMethod.GET, headers = "Accept=application/json")
public ApiResponseObject ciphertext(@Param("input") String input) {
Map<String, Object> keyMap;
byte[] cipherText;
try {
keyMap=mncr.initKey();
String publicKey = mncr.getPublicKeyStr(keyMap);
String privateKey = mncr.getPrivateKeyStr(keyMap);
cipherText=mncr.encrypt(input.getBytes(),publicKey);
String keySthring=mncr.encryptBASE64(cipherText);
key.setCiphertext(keySthring);
key.setPrivateKey(privateKey);
}catch (Exception e){
e.printStackTrace();
return reponseJSON(ApiResponseEnum.FAIL.getCode(),ApiResponseEnum.FAIL.getName(),new AjaxResult(false,"失败"));
}
return reponseJSON(ApiResponseEnum.SUCCESS.getCode(),ApiResponseEnum.SUCCESS.getName(),key);
}
@ResponseBody
@RequestMapping(value = "/ciphertextDecryption", method = RequestMethod.POST, headers = "Accept=application/json")
public ApiResponseObject ciphertextDecryption(@RequestBody Key key){
byte[] plainText = new byte[0];
try {
System.out.println(key);
byte[] keyByte=mncr.decryptBASE64(key.getCiphertext());
plainText = mncr.decrypt(keyByte, key.getPrivateKey());
}catch (Exception e){
e.printStackTrace();
}
return reponseJSON(ApiResponseEnum.SUCCESS.getCode(),ApiResponseEnum.SUCCESS.getName(),new String(plainText));
}
@ResponseBody
@RequestMapping(value = "/sendSignature", method = RequestMethod.GET, headers = "Accept=application/json")
public ApiResponseObject sendSignature(@Param("signature") String signatures) {
Map<String, Object> keyMap;
byte[] signature;
try {
keyMap=mncr.initKey();
String publicKey = mncr.getPublicKeyStr(keyMap);
String privateKey = mncr.getPrivateKeyStr(keyMap);
System.out.println("\n原文:" + signatures);
signature= mncr.sign(signatures.getBytes(), privateKey);
String signatureContent=mncr.encryptBASE64(signature);
key.setSignature(signatures);
key.setSignatureContent(signatureContent);
key.setPublicKey(publicKey);
System.out.println("被签名的内容--------"+new String(signature));
boolean status = mncr.verify(signatures.getBytes(), signature, publicKey);
}catch (Exception e){
e.printStackTrace();
return reponseJSON(ApiResponseEnum.FAIL.getCode(),ApiResponseEnum.FAIL.getName(),new AjaxResult(false,"失败"));
}
return reponseJSON(ApiResponseEnum.SUCCESS.getCode(),ApiResponseEnum.SUCCESS.getName(),key);
}
@ResponseBody
@RequestMapping(value = "/signatureVerification", method = RequestMethod.GET, headers = "Accept=application/json")
public ApiResponseObject signatureVerification(@RequestBody Key key){
try {
byte[] signatureContent=mncr.decryptBASE64(key.getSignatureContent());
boolean status = mncr.verify(key.getSignature().getBytes(), signatureContent, key.getPublicKey());
if (status){
return reponseJSON(ApiResponseEnum.SUCCESS.getCode(),ApiResponseEnum.SUCCESS.getName(),new AjaxResult(false,"成功"));
}
}catch (Exception e){
e.printStackTrace();
}
return reponseJSON(ApiResponseEnum.FAIL.getCode(),ApiResponseEnum.FAIL.getName(),new AjaxResult(false,"失败"));
}
@ResponseBody
@RequestMapping(value = "/publicKey", method = RequestMethod.GET, headers = "Accept=application/json")
public ApiResponseObject publicKey() {
Map<String, Object> keyMap;
Map<String,String> map = new HashMap<>();
try {
keyMap=mncr.initKey();
String publicKey = mncr.getPublicKeyStr(keyMap);
String privateKey = mncr.getPrivateKeyStr(keyMap);
map.put("publicKey",publicKey);
map.put("privateKey",privateKey);
}catch (Exception e){
e.printStackTrace();
return reponseJSON(ApiResponseEnum.FAIL.getCode(),ApiResponseEnum.FAIL.getName(),new AjaxResult(false,"失败"));
}
return reponseJSON(ApiResponseEnum.SUCCESS.getCode(),ApiResponseEnum.SUCCESS.getName(),map);
}
}
package com.zjjhy.model;
public class Key {
private String publicKey;
private String privateKey;
private String ciphertext;
private String plaintext;
private String signature;
private String signatureContent;
public String getPublicKey() {
return publicKey;
}
public void setPublicKey(String publicKey) {
this.publicKey = publicKey;
}
public String getPrivateKey() {
return privateKey;
}
public void setPrivateKey(String privateKey) {
this.privateKey = privateKey;
}
public String getCiphertext() {
return ciphertext;
}
public void setCiphertext(String ciphertext) {
this.ciphertext = ciphertext;
}
public String getPlaintext() {
return plaintext;
}
public void setPlaintext(String plaintext) {
this.plaintext = plaintext;
}
public String getSignature() {
return signature;
}
public void setSignature(String signature) {
this.signature = signature;
}
public String getSignatureContent() {
return signatureContent;
}
public void setSignatureContent(String signatureContent) {
this.signatureContent = signatureContent;
}
@Override
public String toString() {
return "Key{" +
"publicKey='" + publicKey + '\'' +
", privateKey='" + privateKey + '\'' +
", ciphertext='" + ciphertext + '\'' +
", plaintext='" + plaintext + '\'' +
", signature='" + signature + '\'' +
", signatureContent='" + signatureContent + '\'' +
'}';
}
}