使用Java的数字签名电子令牌的空指针异常密钥库

时间:2019-02-07 12:02:42

标签: java nullpointerexception listiterator

我正面临

  使用Java从数字签名电子令牌中

NullPointerException

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfEncryptor;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfSignatureAppearance;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.security.BouncyCastleDigest;
import com.itextpdf.text.pdf.security.CertificateUtil;
import com.itextpdf.text.pdf.security.CrlClient;
import com.itextpdf.text.pdf.security.CrlClientOnline;
import com.itextpdf.text.pdf.security.DigestAlgorithms;
import com.itextpdf.text.pdf.security.ExternalDigest;
import com.itextpdf.text.pdf.security.ExternalSignature;
import com.itextpdf.text.pdf.security.MakeSignature;
import com.itextpdf.text.pdf.security.MakeSignature.CryptoStandard;
import com.itextpdf.text.pdf.security.OcspClient;
import com.itextpdf.text.pdf.security.OcspClientBouncyCastle;
import com.itextpdf.text.pdf.security.PrivateKeySignature;
import com.itextpdf.text.pdf.security.TSAClient;
import com.itextpdf.text.pdf.security.TSAClientBouncyCastle;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.math.BigInteger;
import java.nio.file.CopyOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.security.GeneralSecurityException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateNotYetValidException;
import java.security.cert.CertificateParsingException;
import java.security.cert.X509Certificate;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;

public class Signature {
    public static ArrayList b = new ArrayList();
    public static String userName = new com.sun.security.auth.module.NTSystem().getName();
    public static String srcPath = null;
    public static String destPath = null;
    public static String smtp = null;
    public static String pin = null;
    public static String Mac;
    public static String destina;
    public static String tempsrc;
    public static String temp;
    public static PrivateKey pk;
    public static DateFormat dateFormat;
    public static String line;
    public static Document document;
    public static String alias = null;
    public static BufferedReader bufferedReader;
    public static File[] listOfFiles;
    public static X509Certificate cert;
    public static OcspClient ocspClient;
    public static TSAClient tsaClient = null;
    public static Certificate[] chain;
    public static java.security.KeyStore keyStore;
    public static java.io.ByteArrayInputStream pkcs11ConfigStream;
    public static sun.security.pkcs11.SunPKCS11 providerPKCS11;
    public static java.security.Provider p;
    public static JPasswordField pf;
    public static String pkcs11Config;
    public static final JPanel panel = new JPanel();
    public static FileWriter fw;
    public static Date date;
    public static BigInteger serialNo;

    public static void main(String args[]) throws IOException, GeneralSecurityException, DocumentException,
            CertificateVerificationException, ParseException {
        System.out.println("Digital Signature Process Starts...");
        File dpath = new File("C:\\Users\\" + System.getProperty("user.name") + "\\AppData\\Local\\Temp");
        if (!dpath.exists()) {
            dpath.mkdirs();
        }
        dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        date = new Date();
        // System.out.println(dateFormat.format(date));
        fw = new FileWriter(dpath + "\\log.txt");
        try {
            fw.write("S01-Application started" + " ~ " + dateFormat.format(date));
        } catch (Exception e) {
            System.out.println(e);
        }
        //try {
        String my_date = "31/12/9999";
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        Date strDate = sdf.parse(my_date);
        if (new Date().after(strDate)) {
            try {
                fw.write("\r\n");
                fw.write("E01-Appication is out dated,exiting" + " ~ " + dateFormat.format(date));
                fw.write("\r\n");
                fw.write("S15-Application Ends" + " ~ " + dateFormat.format(date));
                fw.close();
            } catch (Exception e) {
                System.out.println(e);
            }
            // JOptionPane.showMessageDialog(panel, "Your Application is
            // outdated", "Error", JOptionPane.ERROR_MESSAGE);
            System.exit(0);
        } else {
            try {
                fw.write("\r\n");
                fw.write("S02-Valid Application" + " ~ " + dateFormat.format(date));
            } catch (Exception e) {
                System.out.println(e);
            }
            try {
                Class<?> pkcs11Class = Class.forName("sun.security.pkcs11.SunPKCS11");
                Constructor<?> construct = pkcs11Class.getConstructor(new Class[] { String.class });
                pkcs11Config = "C:\\Users\\" + userName + "\\Documents\\Config\\pkcs11.cfg"; // eps2003csp11 //
                                                                                                // TRUSTKEYP11_ND_v34.dll";
                                                                                                // //eMudhraP11_ND_v34.dll"
                                                                                                // ;//
                p = (Provider) construct.newInstance(new Object[] { pkcs11Config });
                // Security.addProvider(p);
            } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException
                    | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                fw.write("\r\n");
                fw.write("E03-Digital signature is not installed" + " ~ " + dateFormat.format(date));
                fw.write("\r\n");
                fw.write("S15-Application Ends" + " ~ " + dateFormat.format(date));
                fw.close();
            }
            try {
                fw.write("\r\n");
                fw.write("S03-Digital signature is  installed perfectly" + " ~ " + dateFormat.format(date));
            } catch (Exception e) {
                System.out.println(e);
            }
            try {
                java.security.Security.addProvider(p);
                keyStore = java.security.KeyStore.getInstance("PKCS11", p);
                pf = new JPasswordField();
            } catch (Exception e) {
                fw.write("\r\n");
                fw.write("E04-USB-Key is Not found" + " ~ " + dateFormat.format(date));
                fw.write("\r\n");
                fw.write("S15-Application Ends" + " ~ " + dateFormat.format(date));
                fw.close();
                System.exit(0);
            }
            try {
                fw.write("\r\n");
                fw.write("S04-USB-key is Detected" + " ~ " + dateFormat.format(date));
            } catch (Exception e) {
                System.out.println(e);
            }
            int result = JOptionPane.showConfirmDialog(null, pf, "Please Enter your Digital Signature PIN",
                    JOptionPane.OK_CANCEL_OPTION);
            if (result == JOptionPane.OK_OPTION) {
                pin = new String(pf.getPassword());
            } else {
                //JOptionPane.showMessageDialog(panel, "Process Canceled", "Error", JOptionPane.ERROR_MESSAGE);
                fw.write("\r\n");
                fw.write("E05-Cancelled the Enter password" + " ~ " + dateFormat.format(date));
                fw.write("\r\n");
                fw.write("S15-Application Ends" + " ~ " + dateFormat.format(date));
                fw.close();
                System.exit(0);
            }
            if (keyStore != null) {
                try {
                    keyStore.load(null, pin.toCharArray());
                    java.util.Enumeration<String> aliases = keyStore.aliases();
                    // String alias = null;
                    ArrayList Certtificates = new ArrayList();
                    while (aliases.hasMoreElements()) {
                        alias = aliases.nextElement();
                        Certtificates.add(alias);
                        // System.out.println(alias);
                    }
                    for (Object Certtificate : Certtificates) {
                        alias = (String) Certtificate;
                        //System.out.println(alias);
                        pk = (PrivateKey) keyStore.getKey(alias, pin.toCharArray());
                        if (pk != null) {
                            System.out.println(alias);
                            chain = keyStore.getCertificateChain(alias);
                            for (Certificate chain1 : chain) {
                                X509Certificate cert = (X509Certificate) chain1;
                                cert.checkValidity();
                            }
                            break;
                        }
                    }
                } catch (IOException | NoSuchAlgorithmException | CertificateException | KeyStoreException
                        | UnrecoverableKeyException e) {
                    fw.write("\r\n");
                    fw.write("E06-Wrong Password entered" + " ~ " + dateFormat.format(date));
                    fw.write("\r\n");
                    fw.write("S15-Application Ends" + " ~ " + dateFormat.format(date));
                    fw.close();
                    System.exit(0);
                }
                try {
                    fw.write("\r\n");
                    fw.write("S06-Correct Password Entered" + " ~ " + dateFormat.format(date));
                } catch (Exception e) {
                    System.out.println(e);
                }
                // chain = keyStore.getCertificateChain(alias);
                ocspClient = new OcspClientBouncyCastle();
                try {
                    System.out.println(chain);
                    for (Certificate chain : chain) {
                        //System.out.println("ASCDCADSEA"+chain);
                        cert = (X509Certificate) chain;
                        cert.checkValidity();
                        //cert.verify(cert.getPublicKey());
                        Collection<List<?>> List = cert.getSubjectAlternativeNames();
                        System.out.println("ZZZZZZZZZZZZ" + List);
                        serialNo = cert.getSerialNumber();
                        //System.out.println("mmmmmnm"+chain);
                        System.out.println(serialNo);
                        Iterator<List<?>> iterator = List.iterator();
                        while (iterator.hasNext()) {
                            List<?> test = iterator.next();
                            smtp = (String) test.get(1);
                        }
                        break;
                    }
                } catch (CertificateExpiredException | CertificateNotYetValidException
                        | CertificateParsingException e) {
                    fw.write("\r\n");
                    fw.write("E07-Certificate validity expired" + " ~ " + dateFormat.format(date));
                    fw.write("\r\n");
                    fw.write("S15-Application Ends" + " ~ " + dateFormat.format(date));
                    fw.close();
                    System.exit(0);
                }
                try {
                    fw.write("\r\n");
                    fw.write("S07-Certificate has validity" + " ~ " + dateFormat.format(date));
                } catch (Exception e) {
                    System.out.println(e);
                }
                String[] Split = smtp.split("@");
                String str = Split[1];
                //System.out.println(str);
                if ("abc.co.in".equals(str) || "abc.CO.IN".equals(str) || "abc.COM".equals(str)
                        || "abc.com".equals(str)) {
                    fw.write("\r\n");
                    fw.write("S08-Valid User" + " ~ " + dateFormat.format(date));
                } else {
                    //JOptionPane.showMessageDialog(panel, "Invalid User", "Error", JOptionPane.ERROR_MESSAGE);
                    fw.write("\r\n");
                    fw.write("E08-Not Valid User" + " ~ " + dateFormat.format(date));
                    fw.write("\r\n");
                    fw.write("S15-Application Ends" + " ~ " + dateFormat.format(date));
                    fw.close();
                    System.exit(0);
                }
                String tsaUrl = CertificateUtil.getTSAURL(cert);
                if (tsaUrl != null) {
                    tsaClient = new TSAClientBouncyCastle(tsaUrl);
                    return;
                }
            }
            List<CrlClient> crlList = new ArrayList<>();
            crlList.add(new CrlClientOnline(chain));
            Signature t = new ITEANZ_IDES_V5_TAFE();
            ArrayList a = new ArrayList();
            try {
                FileReader fileReader = new FileReader(
                        "C:\\Users\\" + userName + "\\AppData\\Local\\Temp\\temp\\temp.txt");
                bufferedReader = new BufferedReader(fileReader);
            } catch (Exception e) {
                fw.write("\r\n");
                fw.write("E09-Temporary Text file is not availble" + " ~ " + dateFormat.format(date));
                fw.write("\r\n");
                fw.write("S15-Application Ends" + " ~ " + dateFormat.format(date));
                fw.close();
                System.exit(0);
            }
            try {
                fw.write("\r\n");
                fw.write("S09-Temporary Text file is availble" + " ~ " + dateFormat.format(date));
            } catch (Exception e) {
                System.out.println(e);
            }
            while ((line = bufferedReader.readLine()) != null) {
                a.add(line);
            }
            System.out.println(a.size());
            if (a.size() != 3) {
                fw.write("\r\n");
                fw.write("E10-Data is not maintained Properly" + " ~ " + dateFormat.format(date));
                fw.write("\r\n");
                fw.write("S15-Application Ends" + " ~ " + dateFormat.format(date));
                fw.close();
                System.exit(0);
            } else {
                srcPath = a.get(1).toString();
                destPath = a.get(2).toString();
                try {
                    fw.write("\r\n");
                    fw.write("S10-Data is maintained Properly" + " ~ " + dateFormat.format(date));
                } catch (Exception e) {
                    System.out.println(e);
                }
            }
            // System.out.println(a.get(3).toString());
            try {
                if (serialNo.toString() == null ? a.get(3).toString().trim() == null
                        : serialNo.toString().equals(a.get(3).toString().trim())) {
                    fw.write("\r\n");
                    fw.write("S11- Authoraised User" + " ~ " + dateFormat.format(date));
                } else {
                    fw.write("\r\n");
                    fw.write("E11- Un-Authoraised User" + " ~ " + dateFormat.format(date));
                    fw.write("\r\n");
                    fw.write("S15-Application Ends" + " ~ " + dateFormat.format(date));
                    fw.close();
                    System.exit(0);
                }
            } catch (Exception e) {
                System.out.println(e);
            }
            File dir = new File(destPath);
            dir.mkdirs();
            File folder = new File(srcPath);
            listOfFiles = folder.listFiles();
            if (listOfFiles.length == 0) {
                fw.write("\r\n");
                fw.write("E12-No files Found inside Input folder" + " ~ " + dateFormat.format(date));
                fw.write("\r\n");
                fw.write("S15-Application Ends" + " ~ " + dateFormat.format(date));
                fw.close();
                System.exit(0);
            }
            if (listOfFiles.length != 0) {
                for (File file : listOfFiles) {
                    if (file.isFile()) {
                        String userFile = srcPath + "/" + file.getName();
                        String IndividualFileNAme = file.getName();
                        String userFile_signed = dir + "/" + file.getName();
                        t.sign(userFile, IndividualFileNAme, userFile_signed, chain, pk, DigestAlgorithms.SHA256,
                                p.getName(), CryptoStandard.CMS, "Document Approval", "Bangalore", crlList, ocspClient,
                                tsaClient, 0);
                    }
                }
            }
            try {
                fw.write("\r\n");
                fw.write("S12-File is inside the Input folder" + " ~ " + dateFormat.format(date));
            } catch (Exception e) {
                System.out.println(e);
            }
            File srcDir = new File(srcPath);
            int numberSrcFiles = srcDir.listFiles().length;
            File destDir = new File(destPath);
            int numberDestFiles = destDir.listFiles().length;
            if (numberDestFiles == numberSrcFiles) {
                //JOptionPane.showMessageDialog(panel, "Documents are Signed Successfully", "Success",
                //JOptionPane.INFORMATION_MESSAGE);
                try {
                    PrintWriter writer = new PrintWriter(
                            "C:\\Users\\" + userName + "\\AppData\\Local\\Temp\\temp\\output.txt", "UTF-8");
                    writer.println("X");
                    writer.close();
                    fw.write("\r\n");
                    fw.write("S14-Documents are Signed Successfully" + " ~ " + dateFormat.format(date));
                } catch (Exception e) {
                    System.out.println(e);
                }
            } else {
                //JOptionPane.showMessageDialog(panel, "Some Documents Are Missing", "Error",
                //  JOptionPane.ERROR_MESSAGE);
                fw.write("\r\n");
                fw.write("E15-Some Documents Are Missing" + " ~ " + dateFormat.format(date));
                fw.write("\r\n");
                fw.write("S15-Application Ends" + " ~ " + dateFormat.format(date));
                fw.close();
                System.exit(0);
            }
            System.out.println("Digital Signature Process Ends...");
            try {
                fw.write("\r\n");
                fw.write("S15-Application Ends" + " ~ " + dateFormat.format(date));
                fw.close();
            } catch (Exception e) {
                System.out.println(e);
            }
            System.exit(0);
        }
    }

    public void sign(String src, String FinalFileName, String dest, Certificate[] chain, PrivateKey pk,
            String digestAlgorithm, String provider, CryptoStandard subfilter, String reason, String location,
            Collection<CrlClient> crlList, OcspClient ocspClient, TSAClient tsaClient, int estimatedSize)
            throws GeneralSecurityException, IOException, DocumentException {
        try {
            tempsrc = "C:\\Users\\" + userName + "\\AppData\\Local\\Temp\\DigitalSiganture\\Signed_temp.pdf";
            temp = "C:\\Users\\" + userName + "\\AppData\\Local\\Temp\\DigitalSiganture\\";
            File dir = new File(temp);
            dir.mkdirs();
            document = new Document();
            PdfReader reader6 = new PdfReader(tempsrc);
            PdfStamper stamper6 = new PdfStamper(reader6, new FileOutputStream(dest));
            stamper6.setEncryption("cp123".getBytes(), "".getBytes(), PdfWriter.ALLOW_COPY,
                    PdfWriter.ENCRYPTION_AES_256);
            stamper6.close();
            reader6.close();
            PdfWriter.getInstance(document, new FileOutputStream(tempsrc));
            document.open();
            // step 4
            document.add(new Paragraph("Hello World!"));
            // step 5
            document.close();
            PdfReader reader = new PdfReader(src);
            Path FROM = Paths.get(src);
            Path TO = Paths.get(tempsrc);
            // overwrite existing file, if exists
            CopyOption[] options = new CopyOption[] { StandardCopyOption.REPLACE_EXISTING,
                    StandardCopyOption.COPY_ATTRIBUTES };
            Files.copy(FROM, TO, options);
            int ret = reader.getNumberOfPages();
            for (int x = 0; x < ret; x++) {
                destina = "Signed_temp" + x + ".pdf";
                FileOutputStream os = new FileOutputStream(temp + destina);
                PdfReader reader1 = new PdfReader(tempsrc);
                tempsrc = temp + destina;
                PdfStamper stamper = PdfStamper.createSignature(reader1, os, '\0', null, true);
                PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
                appearance.setCertificationLevel(PdfSignatureAppearance.NOT_CERTIFIED);
                // appearance.setReason(reason);
                // appearance.setLocation(location);
                String signname = "Sign" + x;
                int y = x + 1;
                appearance.setAcro6Layers(false);
                appearance.setLayer4Text(PdfSignatureAppearance.questionMark);
                appearance.setVisibleSignature(new Rectangle(430, 130, 550, 90), y, signname);
                ExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm, provider);
                ExternalDigest digest = new BouncyCastleDigest();
                MakeSignature.signDetached(appearance, digest, pks, chain, crlList, ocspClient, tsaClient,
                        estimatedSize, subfilter);
            }
            try {
                fw.write("\r\n");
                fw.write("S13-" + FinalFileName + " " + "Signed Successfully" + " ~ " + dateFormat.format(date));
            } catch (Exception e) {
                System.out.println(e);
            }
            Path FROM1 = Paths.get(temp + destina);
            Path TO1 = Paths.get(dest);
            //overwrite existing file, if exists
            CopyOption[] options1 = new CopyOption[] { StandardCopyOption.REPLACE_EXISTING,
                    StandardCopyOption.COPY_ATTRIBUTES };
            Files.copy(FROM1, TO1, options1);
            /*
             * //PdfReader.unethicalreading = true; PdfReader reader5=new PdfReader(temp +
             * destina);
             * 
             * PdfEncryptor.encrypt(reader5, new FileOutputStream(dest), null, null,
             * PdfWriter.ALLOW_SCREENREADERS, true);
             */
        } catch (IOException | GeneralSecurityException | DocumentException e) {
            //JOptionPane.showMessageDialog(panel, e, "Error", JOptionPane.ERROR_MESSAGE);
            fw.write("\r\n");
            fw.write("E14-" + FinalFileName + "Format mismatch or File Crashed " + " ~ " + dateFormat.format(date));
            fw.write("\r\n");
            fw.write("S15-Application Ends" + " ~ " + dateFormat.format(date));
            fw.close();
            System.exit(0);
        }
    }
}
  

NullPointerException Iterator<List<?>> iterator = List.iterator();

在程序执行期间,证书值会在读取时出现,但是当我尝试将其存储在List中时,它将变成null。实际上,我想阅读存储有证书的数字签名的USB加密狗,并且需要将签名放入特定位置的PDF文件中。

在读取USB Epass2003时需要对代码进行一些修正

2 个答案:

答案 0 :(得分:0)

在代码的这一部分:

Collection<List<?>> List = cert.getSubjectAlternativeNames();

方法getSubjectAlternativeNames()返回null导致NPE。观察一下,在Java中,变量的名称通常以小写字母开头,名称为List的列表很奇怪

答案 1 :(得分:0)

方法.iterator()实例方法,不能不能称为静态方法。似乎您应该致电List.Iterator()时正在致电someList.iterator()

只需遍历List,就可以

List<Integer> integerList = Arrays.asList(1, 2, 3, 4);
    for (Integer x : integerList)
        System.out.println(x);