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

com.geotab.model.serialization.X509CertificateSerializer Maven / Gradle / Ivy

/*
 *
 * 2020 Copyright (C) Geotab Inc. All rights reserved.
 */

package com.geotab.model.serialization;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class X509CertificateSerializer extends JsonSerializer {

  @Override
  public void serialize(X509Certificate x509Certificate, JsonGenerator jsonGenerator,
      SerializerProvider serializerProvider) throws IOException {
    if (x509Certificate == null) {
      jsonGenerator.writeNull();
    } else {
      try {
        jsonGenerator.writeString(byteArrayToHex(x509Certificate.getEncoded()));
      } catch (CertificateEncodingException e) {
        log.error("Can not serialize certificate", e);
        jsonGenerator.writeNull();
      }
    }
  }

  private String byteArrayToHex(byte[] bytes) {
    StringBuilder result = new StringBuilder(bytes.length * 2);
    String hexAlphabet = "0123456789ABCDEF";
    for (byte b : bytes) {
      result
          .append(hexAlphabet.charAt((b & 0xFF) >> 4))
          .append(hexAlphabet.charAt(b & 0xF));
    }
    return result.toString();
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy