美文网首页
怎么导入 java.util.Base64 到 Android

怎么导入 java.util.Base64 到 Android

作者: 黑键手记 | 来源:发表于2019-01-22 12:25 被阅读66次

    java 的提取证书的方法,其中用到了java 中的 base64包

      import java.io.File;
      import java.io.FileInputStream;
      import java.io.IOException;
      import java.io.InputStream;
      import java.security.MessageDigest;
      import java.security.cert.CertificateFactory;
      import java.security.cert.X509Certificate;
      import java.util.Arrays;
      import java.util.Base64;
    
      public class PeerCertificateExtractor {
    /**
     * Get peer certificate(Public key to sha256 to base64)
     * @param certificate Crt or der or pem file with a valid certificate
     * @return
     */
    public static String extract(File certificate){
    
        FileInputStream inputStream = null;
    
        try{
            inputStream = new FileInputStream(certificate);
            X509Certificate x509Certificate = (X509Certificate) CertificateFactory.getInstance("X509")
                    .generateCertificate(inputStream);
    
            byte[] publicKeyEncoded = x509Certificate.getPublicKey().getEncoded();
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
            byte[] publicKeySha256 = messageDigest.digest(publicKeyEncoded);
            byte[] publicKeyShaBase64 = Base64.getEncoder().encode(publicKeySha256);
    
           return "sha256/" + new String(publicKeyShaBase64);
        }catch (Exception e){
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";
    }
    }
    

    而在 android 当中,你应该删除下列代码

     byte[] publicKeyShaBase64 = Base64.getEncoder().encode(publicKeySha256);
     return "sha256/" + new String(publicKeyShaBase64);
    

    然后替换成

    return "sha256/" + Base64.encodeToString(publicKeySha256, Base64.DEFAULT);

    相关文章

      网友评论

          本文标题:怎么导入 java.util.Base64 到 Android

          本文链接:https://www.haomeiwen.com/subject/qesljqtx.html