我正在使用java apns为了向我的服务器上的 ios 设备推送通知,Java apns 在推送通知时需要 .p12 证书和密码。
ApnsService service =
APNS.newService()
.withCert("/path/to/certificate.p12", "MyCertPassword")
.withSandboxDestination()
.build();
我想将这种类型的 .p12 存储到我的数据库中,因为我的系统中有超过 1 个 .p12 文件。我们的服务器还允许第三方将他们的应用程序提交到我们的服务器。他们需要将 .p12 文件提交到我们的服务器,因为他们想通过我们的服务器推送通知。我们不想将他们的 .p12 文件保存到我们服务器上的文件夹中,而是保存到带有 base64 字符串的数据库中。
我有一些问题:
我们如何将 .p12 转换为 Base64 字符串?
当我推送通知时,如何从 Base64 字符串恢复 .p12 文件?
有没有更好的解决方案来在我的服务器端获取和存储 .p2 文件?
提前致谢。
最佳答案
private static String encodeFileToBase64Binary(String fileName)
throws IOException {
File file = new File(fileName);
byte[] bytes = loadFile(file);
byte[] encoded = Base64.encodeBase64(bytes);
String encodedString = new String(encoded);
return encodedString;
}
private static byte[] loadFile(File file) throws IOException {
InputStream is = new FileInputStream(file);
long length = file.length();
if (length > Integer.MAX_VALUE) {
// File is too large
}
byte[] bytes = new byte[(int)length];
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
offset += numRead;
}
if (offset < bytes.length) {
throw new IOException("Could not completely read file "+file.getName());
}
is.close();
return bytes;
}
关于ios - 如何将p12文件转换为base64字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26821644/