RSA, Jackson, and DecimalFormat

package com.sf.test.json;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.text.DecimalFormat;

public class DoubleSerializer extends JsonSerializer<Double> {

    public static DecimalFormat decimalFormat = new DecimalFormat("##.0");

    @Override
    public void serialize(Double aDouble, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
        jsonGenerator.writeString(decimalFormat.format(aDouble));
    }

}
package com.sf.test.json;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

import java.io.IOException;
import java.time.LocalDateTime;

public class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {

    @Override
    public LocalDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        return LocalDateTime.parse(jsonParser.getText(), LocalDateTimeSerializer.DATETIME_FORMATTER);
    }
}
package com.sf.test.json;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {

    public static DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd, HHmmss");

    @Override
    public void serialize(LocalDateTime localDateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
        jsonGenerator.writeString(LocalDateTime.now().format(DATETIME_FORMATTER));
    }

}
package com.sf.test.dto;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.sf.test.json.DoubleSerializer;
import com.sf.test.json.LocalDateTimeDeserializer;
import com.sf.test.json.LocalDateTimeSerializer;

import java.time.LocalDateTime;

@JsonIgnoreProperties(value = {"code"})
public class CryptoDto {

    private String data;
    private Integer code;
    private Long expires;
    @JsonSerialize(using = LocalDateTimeSerializer.class)
    @JsonDeserialize(using = LocalDateTimeDeserializer.class)
    private LocalDateTime now;
    @JsonSerialize(using = DoubleSerializer.class)
    private Double aDouble = 56565.13131313;

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("{data: ");
        sb.append(data);
        sb.append(", code: ");
        sb.append(code);
        sb.append(", expires: ");
        sb.append(expires);
        sb.append(", now: ");
        sb.append(now);
        sb.append(", aDouble: ");
        sb.append(aDouble);
        sb.append("}");
        return sb.toString();
    }

    public CryptoDto() {
    }

    public CryptoDto(String data, Long expires) {
        this.data = data;
        this.expires = expires;
        this.now = LocalDateTime.now();
    }

    public CryptoDto(String data, Integer code, Long expires) {
        this.data = data;
        this.code = code;
        this.expires = expires;
        this.now = LocalDateTime.now();
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public Long getExpires() {
        return expires;
    }

    public void setExpires(Long expires) {
        this.expires = expires;
    }

    public LocalDateTime getNow() {
        return now;
    }

    public void setNow(LocalDateTime now) {
        this.now = now;
    }

    public Double getaDouble() {
        return aDouble;
    }

    public void setaDouble(Double aDouble) {
        this.aDouble = aDouble;
    }

}
package com.sf.test;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sf.test.dto.CryptoDto;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

public class RSAUtil {

    private static Map<Integer, String> KEY_MAP = new HashMap<>();
    private static String PRIVATE_KEY_STR;
    private static String PUBLIC_KEY_STR;

    static {
        try {
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            keyPairGenerator.initialize(1024, new SecureRandom());
            KeyPair keyPair = keyPairGenerator.genKeyPair();
            PrivateKey privateKey = keyPair.getPrivate();
            PublicKey publicKey = keyPair.getPublic();
            String privateKeyStr = new String(Base64.encodeBase64(privateKey.getEncoded()));
            String publicKeyStr = new String(Base64.encodeBase64(publicKey.getEncoded()));
            KEY_MAP.put(0, privateKeyStr);
            KEY_MAP.put(1, publicKeyStr);

            PRIVATE_KEY_STR = KEY_MAP.get(0);
            PUBLIC_KEY_STR = KEY_MAP.get(1);

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    public static String encrypt(String str, String publicKeyStr) throws Exception {
        byte[] decoded = Base64.decodeBase64(publicKeyStr);
        PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes(StandardCharsets.UTF_8)));
        return outStr;
    }

    public static String decrypt(String str, String privateKeyStr) throws Exception {
        byte[] inputBytes = Base64.decodeBase64(str.getBytes(StandardCharsets.UTF_8));
        byte[] decoded = Base64.decodeBase64(privateKeyStr);
        PrivateKey privateKey = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        String outStr = new String(cipher.doFinal(inputBytes));
        return outStr;
    }

    public static String encrypt(String str) throws Exception {
        return encrypt(str, PUBLIC_KEY_STR);
    }

    public static String decrypt(String str) throws Exception {
        return decrypt(str, PRIVATE_KEY_STR);
    }

    public static void main(String[] args) {
        try {
            String str = "Whenever I looked back, time blocked my path to retreat.";
            String encryptedStr = RSAUtil.encrypt(str);
            System.out.println(encryptedStr);
            System.out.println(decrypt(encryptedStr));

            CryptoDto cryptoDto = new CryptoDto("She will be loved.", System.currentTimeMillis() - 30000L);
            ObjectMapper objectMapper = new ObjectMapper();
            String decryptedStr = objectMapper.writeValueAsString(cryptoDto);
            System.out.println(decryptedStr);
            CryptoDto deserializedDto = objectMapper.readValue(decryptedStr, CryptoDto.class);
            System.out.println(deserializedDto);
            if (deserializedDto.getExpires() < System.currentTimeMillis()) {
                System.out.println("Token expires.");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值