使用Spring-Boot框架开发Java程序,字符编码问题

Developing a Java program using the Spring-Boot framework, the problem of character encoding

提问人:Vasiliy 提问时间:11/7/2023 最后编辑:khelwoodVasiliy 更新时间:11/7/2023 访问量:34

问:

我的任务是使用 Spring Boot 框架在 Java 中编写一个程序。下面是我为此应用程序编写的代码。问题是,当我从 textarea 中提取文本时,特殊字符和俄语字母没有正确传递给变量,而当消息变量输出到控制台时,获取了用户输入的错误文本。

如何确保没有此类错误?

在网站上输入文本输出:Сообщение получено: File received and decrypted: message=Hello+World%3B+%D0%9F%D1%80%D0%B8%D0%B2%D0%B5%D1%82+%D0%BC%D0%B8%D1%80%3B+1234567890%3B+%21%40%23%24%25%5E%26*%28%29-%2B_%3D%2F%5C%3C%3E%2C.%7E%3B

我试图更改网站和代码中的编码。

下面是网站和客户端应用程序的代码:

package com.mvas.client.controller;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.client.RestTemplate;
import javax.crypto.Cipher;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.Security;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

@Controller
public class ClientController {

    private RSAPublicKey clientPublicKey;
    private RSAPrivateKey clientPrivateKey;
    @GetMapping("/")
    public String toIndex(){
        return "index";
    }

    @PostMapping("/sendMessage")
    public String sendMessage(@RequestBody String message, Model model) {
        try {
            System.out.println(message);
            List<String> encryptedBlocks = encryptWithServerPublicKey(message);
            System.out.println(encryptedBlocks);
            String response = sendEncryptedBlocksToServer(encryptedBlocks);
            model.addAttribute("response", "Сообщение получено: " + response);
            System.out.println(response);
        } catch (Exception e) {
            model.addAttribute("response", "Error: " + e.getMessage());
        }
        return "result";
    }

    private List<String> encryptWithServerPublicKey(String message) throws Exception {
        Security.addProvider(new BouncyCastleProvider());

        RestTemplate restTemplate = new RestTemplate();
        String serverUrl = "http://localhost:8081/getServerPublicKey";
        String serverPublicKeyBase64 = restTemplate.postForObject(serverUrl, null, String.class);
        RSAPublicKey serverPublicKey = decodeRSAPublicKey(serverPublicKeyBase64);
        Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING", "BC");
        cipher.init(Cipher.ENCRYPT_MODE, serverPublicKey);
        System.out.println(cipher);
        byte[] messageBytes = message.getBytes(StandardCharsets.UTF_8);
        int inputLen = messageBytes.length;
        int blockSize = 245;
        List<String> encryptedBlocks = new ArrayList<>();

        for (int i = 0; i < inputLen; i += blockSize) {
            int currentBlockSize = Math.min(blockSize, inputLen - i);
            byte[] block = cipher.doFinal(messageBytes, i, currentBlockSize);
            encryptedBlocks.add(Base64.getEncoder().encodeToString(block));
        }

        return encryptedBlocks;
    }

    private RSAPublicKey decodeRSAPublicKey(String publicKeyBase64) throws Exception {
        byte[] publicKeyBytes = Base64.getDecoder().decode(publicKeyBase64);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes);
        return (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(keySpec);
    }

    private String sendEncryptedBlocksToServer(List<String> encryptedBlocks) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<List<String>> request = new HttpEntity<>(encryptedBlocks, headers);
        RestTemplate restTemplate = new RestTemplate();
        String serverUrl = "http://localhost:8081/receiveFile";
        return restTemplate.postForObject(serverUrl, request, String.class);
    }
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Input Page</title>
</head>
<body>
<h1>Введите сообщение</h1>
<form action="/sendMessage" method="post">
    <textarea type="text" name="message" placeholder="Ваше сообщение" required></textarea>
    <button type="submit">Отправить</button>
</form>
</body>
</html>
Java HTML spring-Boot 编码 Web 应用程序

评论

0赞 Morph21 11/7/2023
我不确定你做错了什么,但你的输出是 URL 编码的,所以你需要 URL 解码器

答: 暂无答案