All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.geotab.model.serialization.serdes.X509CertificateDeserializer Maven / Gradle / Ivy

package com.geotab.model.serialization.serdes;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.geotab.util.Util;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class X509CertificateDeserializer extends JsonDeserializer {

  @Override
  public X509Certificate deserialize(JsonParser jsonParser, DeserializationContext context)
      throws IOException {
    ObjectCodec parserCodec = jsonParser.getCodec();
    JsonNode node = parserCodec.readTree(jsonParser);

    if (node.isTextual()) {
      try {
        return buildX509Certificate(node.textValue());
      } catch (CertificateException e) {
        log.error("Can not create X509Certificate", e);
        return null;
      }

    }

    return null;
  }

  public static X509Certificate buildX509Certificate(String certificateString)
      throws CertificateException {
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    return (X509Certificate) certificateFactory.generateCertificate(
        new ByteArrayInputStream(certificateBytesFromString(certificateString))
    );
  }

  public static byte[] certificateBytesFromString(String certificateString) {
    if (Util.isEmpty(certificateString)) {
      return new byte[0];
    }

    byte[] certificateBytes = new byte[certificateString.length() / 2];
    for (int i = 0; i < certificateBytes.length; i++) {
      certificateBytes[i] = (byte) Integer
          .parseInt(certificateString.substring(i * 2, i * 2 + 2), 16);
    }
    return certificateBytes;
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy