ballchaichana

SignatureProfile

Aug 20th, 2018
205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 11.05 KB | None | 0 0
  1. /*
  2.  * To change this license header, choose License Headers in Project Properties.
  3.  * To change this template file, choose Tools | Templates
  4.  * and open the template in the editor.
  5.  */
  6. package th.in.oneauthen.signing;
  7.  
  8. import java.io.ByteArrayInputStream;
  9. import java.io.File;
  10. import java.io.FileInputStream;
  11. import java.io.IOException;
  12. import java.nio.file.Files;
  13. import java.security.KeyStore;
  14. import java.security.PrivateKey;
  15. import java.security.Security;
  16. import java.security.cert.X509Certificate;
  17. import java.util.ArrayList;
  18. import java.util.Enumeration;
  19.  
  20. import javax.persistence.NoResultException;
  21.  
  22. import org.apache.log4j.Logger;
  23. import org.bouncycastle.jce.provider.BouncyCastleProvider;
  24.  
  25. import th.in.oneauthen.object.SignatureProfileDB;
  26. import th.in.oneauthen.object.DAO.SignatureProfileDAO;
  27.  
  28. /**
  29.  *
  30.  * @author paradorn
  31.  */
  32. public class SignatureProfile {
  33.     private static Logger logger = Logger.getLogger(SignatureProfile.class);
  34.    
  35.     static{
  36.         Security.addProvider(new BouncyCastleProvider());
  37.     }
  38.    
  39.     public static final String PKCS12_INSTANCE = "PKCS12";
  40.     public static final String JKS_INSTANCE = "JKS";
  41.    
  42.     public static SignatureProfile generateNewProfile ( String profileName, byte[] profileKey, String profileKeyPIN, int ownerId ) {
  43.         SignatureProfile profile = null; // String profileName, byte[] profileKey, String profileKeyPIN, int ownerId
  44.         SignatureProfileDB  registeredProfile = null;
  45.            
  46.         registeredProfile = new SignatureProfileDAO().findByNameAndUserUID(profileName, ownerId);
  47.        
  48.         if ( registeredProfile == null ) {
  49.             // No profile setting for this user with this name
  50.             // Start keystore validation process  
  51.             // Load key store
  52.             X509Certificate cert;
  53.             ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>();
  54.             try {
  55.                 KeyStore ks = KeyStore.getInstance(PKCS12_INSTANCE);
  56.                 try{
  57.                     ks.load( new ByteArrayInputStream(profileKey) , profileKeyPIN.toCharArray() );
  58.                 } catch (Exception e){
  59.                     if (e instanceof IOException && e.getMessage().contains("DerInputStream.getLength()")){
  60.                         ks = KeyStore.getInstance(JKS_INSTANCE);
  61.                         ks.load( new ByteArrayInputStream(profileKey) , profileKeyPIN.toCharArray());
  62.                     }else{
  63.                         logger.error("Key store loading failed !!");
  64.                         logger.debug("Key store loading failed !!", e);
  65.                        
  66.                         return profile;
  67.                     }
  68.                 }
  69.                
  70.                 profile = new SignatureProfile();
  71.            
  72.                
  73.                 Enumeration<String> aliases = ks.aliases();
  74.                 while(aliases.hasMoreElements()){
  75.                     // Fetch accessing name from specified key store
  76.                     String alies = aliases.nextElement();
  77.                     if ( ks.isKeyEntry(alies) ){
  78.                         profile.pk = (PrivateKey) ks.getKey(alies, profileKeyPIN.toCharArray());
  79.                         profile.signerCert = (X509Certificate) ks.getCertificate(alies);
  80.                     }
  81.                     cert = (X509Certificate) ks.getCertificate(alies);
  82.                     certList.add(cert);
  83.                 }
  84.             }catch (Exception e) {
  85.                 logger.error(e);
  86.                 return null;
  87.             }
  88.        
  89.             if (profile.pk == null || certList.size()<0){
  90.                 logger.error("Private Key or certificate not found in key store");
  91.                 return null;
  92.             }else{
  93.                 profile.certificateChain = new X509Certificate[certList.size()];
  94.                 profile.certificateChain = certList.toArray(profile.certificateChain);
  95.             }
  96.         } else {
  97.             return null;
  98.         }
  99.        
  100.         return profile;
  101.     }
  102.    
  103.     private SignatureProfile () {
  104.     }
  105.    
  106.     public SignatureProfile ( SignatureProfileDB profileDB ) throws Exception {
  107.        
  108.         // Load key store
  109.         KeyStore ks = KeyStore.getInstance(PKCS12_INSTANCE);;
  110.         try{
  111.             ks.load( new FileInputStream(profileDB.getProfileKey()) , profileDB.getProfileKeyPIN().toCharArray() );
  112.         } catch (Exception e){
  113.             if (e instanceof IOException && e.getMessage().contains("DerInputStream.getLength()")){
  114.                 ks = KeyStore.getInstance(JKS_INSTANCE);
  115.                 ks.load( new FileInputStream(profileDB.getProfileKey()) , profileDB.getProfileKeyPIN().toCharArray());
  116.             }else{
  117.                 logger.error("Key store loading failed !!");
  118.                 logger.debug("Key store loading failed !!", e);
  119.             }
  120.         }
  121.    
  122.         X509Certificate cert;
  123.         ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>();
  124.         Enumeration<String> aliases = ks.aliases();
  125.         while(aliases.hasMoreElements()){
  126.             // Fetch accessing name from specified key store
  127.             String alies = aliases.nextElement();
  128.             if ( ks.isKeyEntry(alies) ){
  129.                 this.pk = (PrivateKey) ks.getKey(alies, profileDB.getProfileKeyPIN().toCharArray());
  130.                 this.signerCert = (X509Certificate) ks.getCertificate(alies);
  131.                 this.keyStoreCommonName= this.signerCert.getSubjectDN().getName().toString();
  132.             }
  133.             cert = (X509Certificate) ks.getCertificate(alies);
  134.             certList.add(cert);
  135.         }
  136.    
  137.         if (this.pk == null || certList.size()<0){
  138.             logger.error("Private Key or certificate not found in key store");
  139.         }else{
  140.             this.certificateChain = new X509Certificate[certList.size()];
  141.             this.certificateChain = certList.toArray(this.certificateChain);
  142.         }
  143.         String docPath = profileDB.getProfileDocDir();
  144.         String docBackupPath = profileDB.getProfileBackupDir();
  145.         String signPath = profileDB.getProfileSignDir();
  146.        
  147.         File docDir, docBackUpDir, signDir;
  148.         if (isNotNull(docPath)){
  149.             docDir = new File(docPath);
  150.             if (docDir.exists() && docDir.isDirectory()){
  151.                 this.setInputDir(docDir);
  152.             }else {
  153.               logger.error("Invalid document directory : "+docPath);
  154.             }
  155.         }
  156.      
  157.         if (isNotNull(docBackupPath)){
  158.             docBackUpDir = new File(docBackupPath);
  159.             if (docBackUpDir.exists() && docBackUpDir.isDirectory()){
  160.                 this.setBackupDir(docBackUpDir);
  161.             }else {
  162.                 logger.error("Invalid document backup directory : "+docBackupPath);
  163.             }
  164.         }
  165.      
  166.         if (isNotNull(signPath)){
  167.             signDir = new File(signPath);
  168.             if (signDir.exists() && signDir.isDirectory()){
  169.                 this.setOutputDir(signDir);
  170.             }else {
  171.                 logger.error("Invalid signed document directory : "+signPath);
  172.             }
  173.         }
  174.        
  175.         if (profileDB.isSigVisible()){
  176.             File sigImg = new File(profileDB.getSigImg());
  177.             String sigLocation = profileDB.getSigLocation();
  178.             if (sigImg.exists() && sigImg.isFile()){
  179.                 this.setSigImg(Files.readAllBytes(sigImg.toPath()));
  180.                 if (isSigLocationCorrect(sigLocation)){
  181.                     this.setSignatureLocation(sigLocation);
  182.                     this.setImagePage(profileDB.getSigDisplayPage());
  183.                     this.setIsVisible(true);
  184.                 }else{
  185.                     logger.error("Signature location for profile "+profileDB.getProfileName()+" is invalid");
  186.                 }
  187.             }else{
  188.                 logger.error("Signature Image for profile "+profileDB.getProfileName()+" is not found or not a file");
  189.             }
  190.         }
  191.     }
  192.    
  193.     String signatureProfileName;
  194.     PrivateKey pk;
  195.     X509Certificate signerCert;
  196.     String keyStoreCommonName;
  197.     X509Certificate[] certificateChain;
  198.    
  199.     File inputDir;
  200.     File backupDir;
  201.     File outputDir;
  202.    
  203.     boolean isVisible = false; 
  204.     byte[] sigImg;
  205.     String signatureLocation;
  206.     int imagePage;
  207.    
  208.     public String getKeyStoreCommonName() {
  209.         return keyStoreCommonName;
  210.     }
  211.  
  212.     public void setKeyStoreCommonName(String keyStoreCommonName) {
  213.         this.keyStoreCommonName = keyStoreCommonName;
  214.     }
  215.  
  216.     public String getSignatureProfileName() {
  217.         return signatureProfileName;
  218.     }
  219.  
  220.     public void setSignatureProfileName(String signatureProfileName) {
  221.         this.signatureProfileName = signatureProfileName;
  222.     }
  223.  
  224.     public PrivateKey getPk() {
  225.         return pk;
  226.     }
  227.  
  228.     public void setPk(PrivateKey pk) {
  229.         this.pk = pk;
  230.     }
  231.  
  232.     public X509Certificate getSignerCert() {
  233.         return signerCert;
  234.     }
  235.  
  236.     public void setSignerCert(X509Certificate signerCert) {
  237.         this.signerCert = signerCert;
  238.     }
  239.  
  240.     public X509Certificate[] getCertificateChain() {
  241.         return certificateChain;
  242.     }
  243.  
  244.     public void setCertificateChain(X509Certificate[] certificateChain) {
  245.         this.certificateChain = certificateChain;
  246.     }
  247.  
  248.     public File getInputDir() {
  249.         return inputDir;
  250.     }
  251.  
  252.     public void setInputDir(File inputDir) {
  253.         this.inputDir = inputDir;
  254.     }
  255.  
  256.     public File getBackupDir() {
  257.         return backupDir;
  258.     }
  259.  
  260.     public void setBackupDir(File backupDir) {
  261.         this.backupDir = backupDir;
  262.     }
  263.  
  264.     public File getOutputDir() {
  265.         return outputDir;
  266.     }
  267.  
  268.     public void setOutputDir(File outputDir) {
  269.         this.outputDir = outputDir;
  270.     }
  271.  
  272.     public boolean isIsVisible() {
  273.         return isVisible;
  274.     }
  275.  
  276.     public void setIsVisible(boolean isVisible) {
  277.         this.isVisible = isVisible;
  278.     }
  279.  
  280.     public byte[] getSigImg() {
  281.         return sigImg;
  282.     }
  283.  
  284.     public void setSigImg(byte[] sigImg) {
  285.         this.sigImg = sigImg;
  286.     }
  287.  
  288.     public static boolean isNotNull (String val){
  289.         if (val == null || val.length() <=0 )
  290.             return false;
  291.         else
  292.             return true;
  293.     }
  294.  
  295.     public int getImagePage() {
  296.         return imagePage;
  297.     }
  298.  
  299.     public void setImagePage(int imagePage) {
  300.         this.imagePage = imagePage-1;
  301.     }
  302.    
  303.     public String getSignatureLocation() {
  304.         return signatureLocation;
  305.     }
  306.  
  307.     public void setSignatureLocation(String signatureLocation) {
  308.         this.signatureLocation = signatureLocation;
  309.     }
  310.  
  311.     public static boolean isSigLocationCorrect (String locationString){
  312.         boolean result = false;
  313.        
  314.         // location syntax = x0:x1:yo:y1 where x1 must > x0 and y1 must > y0
  315.         if (isNotNull(locationString)){
  316.             String[] coordinate = locationString.split(":");
  317.             try{
  318.                 float x0 = Float.parseFloat(coordinate[0]);
  319.                 float x1 = Float.parseFloat(coordinate[1]);
  320.                 float y0 = Float.parseFloat(coordinate[2]);
  321.                 float y1 = Float.parseFloat(coordinate[3]);
  322.                
  323. //                if(x0<x1 && y0<y1)
  324. //                    result = true;
  325.             }catch (Exception e){}
  326.         }
  327.         return result;
  328.     }
  329.    
  330.     public float[] getSignatuerCoOrdinate (){
  331. //        if (isSigLocationCorrect(this.signatureLocation)){
  332.             String[] strCoordinate = this.signatureLocation.split(":");
  333.             float[] coordinate = new float[4];
  334.             for (int i=0; i<4; i++)
  335.                 coordinate[i] = Float.parseFloat(strCoordinate[i]);
  336.            
  337.             return coordinate;
  338. //        }else
  339. //            return null;
  340.     }
  341. }
Advertisement
Add Comment
Please, Sign In to add comment