Sign the mobileconfig file with Java code

一、需要的如下文件:
1、unsigned.mobileconfig(尚未签名的描述文件)
2、sign.itseeker.net.crt (https服务器的证书)
3、sign.itseeker.net.key (https服务器的证书对应的密钥)
4、sign.itseeker.net_nopass.key(无需密码的密钥)
5、ca-bundle.pem (startssl提供的认证机构的证书文件)
6、signed.mobileconfig (输出的签名后的描述文件)

二、openssl签名:
替换了mobileconfig模板文件中的“Check In URL”和“Server URL”的动态参数后,生成了未签名的mbaike.mobileconfig文件,然后通过openssl签名

String content = MdmUtils.readConfig().replace("#deviceId#", deviceId);
 boolean createSuccess = createMobileConfigFile(oldPath,content);
 System.out.println("———————-生成未签名的mobileconfig文件 end———————");
 //签名和认证过程
 if(createSuccess){
      System.out.println("———————-签名mobileconfig文件 start———————");
      String oldCmd = "openssl smime -sign -in {0} -out {1} -signer {2} -inkey {3} -certfile {4} -outform der -nodetach";
      String newCmd = MessageFormat.format(oldCmd,oldPath,newPath,crtPath,keyPath,pemPath);
      Runtime.getRuntime().exec(newCmd);
      System.out.println("———————-签名mobileconfig文件 end———————");
  }

其实就是通过java代码调用 linux的shell命令,可以参考这样的命令:

openssl smime -sign -in unsigned.mobileconfig -out signed.mobileconfig -signer sign.itseeker.net.crt -inkey sign.itseeker.net_nopass.key -certfile sign.itseeker.net.pem -outform der -nodetach

三、mbaikenopass.key文件的生成:

openssl rsa -in sign.itseeker.net.key -out sign.itseeker.net_nopass.key

四、签名后的mobileconfig文件的下载:
可以参考下面的代码:

System.out.println(“———————-下载签名后的mobileconfig文件 start———————”);
response.setHeader(“content-type”, “application/xml;charset=UTF-8”);
response.setCharacterEncoding(“UTF-8”);
String configTitle = “MbaikeApp_”+deviceId;
response.setHeader(“Content-Disposition”, “attachment; filename=” + configTitle + “.mobileconfig”);
/**获取配置文件动态组装参数**/
System.out.println(“———————-下载签名后的mobileconfig文件 end———————”);
java.io.File f = new java.io.File(newPath);
while(true){
     if(f.exists() && f.length()>0){
          java.io.FileInputStream fis = new java.io.FileInputStream(newPath);
          java.io.OutputStream os = response.getOutputStream();
          byte[] b = new byte[1024];
          int i = 0;
          while ((i = fis.read(b)) > 0) {
               os.write(b, 0, i);
          }
          fis.close();
          os.flush();
          os.close();
          break;
     }else{
          continue;
      }
}

关于Zeno Chen

本人涉及的领域较多,杂而不精 程序设计语言: Perl, Java, PHP, Python; 数据库系统: MySQL,Oracle; 偶尔做做电路板的开发,主攻STM32单片机
此条目发表在Java分类目录。将固定链接加入收藏夹。