将证书添加到cacerts文件中

时间:2016-11-23 10:47:36

标签: java keystore filenotfoundexception access-denied

我想通过代码将我的证书添加到cacerts密钥库中,我在下面的代码片段中进行操作。但我得到FileNotFoundException(访问被拒绝)。 我认为发生了什么,因为我没有管理员权限就这样做了。 那么,我该如何解决呢?

package sertificating;

import java.io.*;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;


/**
 * Created by bugakov on 23.11.2016.
 */
public class Sertificating {

    public static void main(String[] argv) throws Exception {
        String certfile = "C:/Users/bugakov/IdeaProjects/school/sertificating/mycert.crt"; 
        String keystorepath=System.getProperties().get("java.home")+"/lib/security/cacerts";
        FileInputStream is = new FileInputStream(keystorepath);
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        keystore.load(is, "changeit".toCharArray());
        String alias = "mycert.crt";
        char[] password = "changeit".toCharArray();
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        InputStream certstream = fullStream(certfile);
        Certificate certs = cf.generateCertificate(certstream);
        File keystoreFile = new File(keystorepath);
        FileInputStream in = new FileInputStream(keystoreFile);
        keystore.load(in, password);
        in.close();
        keystore.setCertificateEntry(alias, certs);
        FileOutputStream out = new FileOutputStream(keystoreFile);
        keystore.store(out, password);
        out.close();

    }

    private static InputStream fullStream(String fname) throws IOException {
        FileInputStream fis = new FileInputStream(fname);
        DataInputStream dis = new DataInputStream(fis);
        byte[] bytes = new byte[dis.available()];
        dis.readFully(bytes);
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        return bais;
    }
}

我得到的例外情况如下:

Exception in thread "main" java.io.FileNotFoundException: C:\Program Files\Java\jdk1.8.0_102\jre\lib\security\cacerts (Access is denied)

在这一行

FileOutputStream out = new FileOutputStream(keystoreFile);

0 个答案:

没有答案