我有一个X509 Certificate
,我希望将其存储在MySQL DB
中,而不是保存文件。因此,我认为最好将证书转换为base64
并存储它。我完成了转换的前进和后退,然而,我没有得到真正的结果。
我正在使用javax.security.cert.X509Certificate
并导入org.apache.commons.codec.binary.Base64
,如下所示:
X509Certificate cert = X509Certificate.getInstance(new FileInputStream(certFile));
System.out.println("Vigencia: "+cert.getNotAfter());
System.out.println("Inicio: "+cert.getNotBefore());
String cert64 = bytes2String(Base64.encodeBase64(cert.toString().getBytes("UTF-8")));
System.out.println("Cert 64: "+ cert64);
String certRegreso = bytes2String(Base64.decodeBase64(cert64.getBytes()));
System.out.println("Cert Regreso: "+ certRegreso);
X509Certificate certNuevo = X509Certificate.getInstance(certRegreso.getBytes());
答案 0 :(得分:10)
根据javadocs X509Certificate实现Serializable,为什么不使用更简单的解决方案并将其存储为字节数组?类似的东西:
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(bos);
out.writeObject(certificate);
byte[] data = bos.toByteArray();
bos.close();
现在只需将字节数组存储为blob。要重新创建它,您可以使用:
ByteArrayIntputSream bis = new ByteArrayInputStream(byteData);
ObjectInput in = new ObjectInputStream(bis);
X509Certificate cert = (X509Certificate) in.readObject();
bis.close();