rabbit51

it's since Nov.30 2005
May.29 2014, transferred from broach

法務省 不動産登記の電子署名用証明書をValidate.javaで検証してみた

2024-07-13 10:00:00 | 

電子署名に使われている証明書の検証を加えてみた。
証明書の発行元(ルート証明書)から電子署名に使われた証明書までの有効性確認(証明書パスと失効)。





法務省 不動産登記の複数人電子署名をValidate.javaで検証してみた」に電子署名用証明書の検証部を加えた(赤文字)。公的個人認証(JPKI)署名用証明書のSubjectAltNameだけでなく政府認証基盤(GPKI)官職証明書のSubjectAltNameに記載されたDistinguishNameも表示するよう対応した(青字)。
Validate.java
import java.io.File;
import java.io.FileInputStream;
import java.security.Key;
import java.security.KeyException;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
import java.security.cert.CertificateParsingException; //--added

import java.security.cert.CertPathBuilder; //--added
import java.security.KeyStore; //--added
import java.security.cert.PKIXParameters; //--added
import java.security.cert.CertPathValidator; //--added
import java.security.cert.Certificate; //--added
import java.security.cert.CertificateFactory; //--added
import java.security.cert.CertPath; //--added
import java.security.cert.CertificateException; //--added
import java.security.cert.CertPathValidatorException; //--added
import java.security.KeyStoreException; //--added
import java.security.NoSuchAlgorithmException; //--added
import java.security.InvalidAlgorithmParameterException; //--added
import java.util.ArrayList; //--added
import java.io.IOException; //--added
import java.security.cert.PKIXRevocationChecker; //--added
import java.security.cert.PKIXRevocationChecker.Option; //--added
import java.util.EnumSet; //--added

import java.util.Iterator;
import java.util.List;
import java.util.HexFormat; //--added
import java.util.Arrays; //--added
import java.util.Collection; //--added
import java.lang.reflect.Array; //--added

import javax.xml.crypto.AlgorithmMethod;
import javax.xml.crypto.KeySelector;
import javax.xml.crypto.KeySelectorException;
import javax.xml.crypto.KeySelectorResult;
import javax.xml.crypto.XMLCryptoContext;
import javax.xml.crypto.XMLStructure;
import javax.xml.crypto.dsig.Reference;
import javax.xml.crypto.dsig.SignatureMethod;
import javax.xml.crypto.dsig.XMLSignature;
import javax.xml.crypto.dsig.XMLSignatureFactory;
import javax.xml.crypto.dsig.dom.DOMValidateContext;
import javax.xml.crypto.dsig.keyinfo.KeyInfo;
import javax.xml.crypto.dsig.keyinfo.KeyValue;
import javax.xml.crypto.dsig.keyinfo.X509Data;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Element;  //-- added

/**
 * This is a simple example of validating an XML Signature using the JSR 105
 * API. It assumes the key needed to validate the signature is contained in a
 * KeyValue KeyInfo.
 */
public class Validate {
	//
	// Synopsis: java Validate [document]
	//
	// where "document" is the name of a file containing the XML document
	// to be validated.
	//
	public static void main(String[] args) throws Exception {
		String fileName = args[0];

		// Instantiate the document to be validated
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		dbf.setNamespaceAware(true);
		Document doc = dbf.newDocumentBuilder().parse(
				new FileInputStream(fileName));

		// Find Signature element
		NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS,
				"Signature");
		if (nl.getLength() == 0) {
			throw new Exception("Cannot find Signature element");
		}

//-- added(外部ファイルのベースディレクトリを指定)
String cpath = new File(fileName).getParent();
cpath = "file://" + cpath.replace('\\', '/') + "/";
System.out.println("setBaseURI-> " + cpath);

//-- added for multiple signature loop
System.out.println("Signature block(s) = " + nl.getLength() );
for ( int k = 0; k < nl.getLength() ; k++ ) {
String SignatureId = nl.item(k).getAttributes().item(0).getNodeValue() ;
System.out.println("\nSignature id = " + SignatureId );

		// Create a DOM XMLSignatureFactory that will be used to unmarshal the
		// document containing the XMLSignature
		XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");

		// Create a DOMValidateContext and specify a KeyValue KeySelector
		// and document context
		DOMValidateContext valContext = new DOMValidateContext(
				new KeyValueKeySelector(), nl.item(k));

//-- added
valContext.setBaseURI(cpath);
//-- added
// 申請用総合ソフト 登録通知
NodeList tg = doc.getElementsByTagName("BODY");
if ( tg.getLength() != 0 ) {
    valContext.setIdAttributeNS( (Element)tg.item(0), null, "ID");
    System.out.println("Find BODY element and setIdAttibute="ID"");
}
// 医療費通知(保険組合)
tg = doc.getElementsByTagName("TEG700");
if ( tg.getLength() != 0 ) {
    valContext.setIdAttributeNS( (Element)tg.item(0), null, "id");
    System.out.println("Find TEG700 element and setIdAttribute="id"");
}
// e-Tax( 所得税 RKO0010. 証明書更新 PTE0010, 電子申請等証明書 TEB120
tg = doc.getElementsByTagName("RKO0010");
if ( tg.getLength() != 0 ) {
    valContext.setIdAttributeNS( (Element)tg.item(0), null, "id");
    System.out.println("Find RKO0010 element and setIdAttribute="id"");
}
tg = doc.getElementsByTagName("PTE0010");
if ( tg.getLength() != 0 ) {
    valContext.setIdAttributeNS( (Element)tg.item(0), null, "id");
    System.out.println("Find PTE0010 element and setIdAttribute="id"");
}
tg = doc.getElementsByTagName("TEB120");
if ( tg.getLength() != 0 ) {
    valContext.setIdAttributeNS( (Element)tg.item(0), null, "id");
    System.out.println("Find TEB120 element and setIdAttribute="id"");
}

 
		// unmarshal the XMLSignature
		XMLSignature signature = fac.unmarshalXMLSignature(valContext);

		// Validate the XMLSignature (generated above)
		boolean coreValidity = signature.validate(valContext);

		// Check core validation status
		if (coreValidity == false) {
			System.err.println("Signature failed core validation");
			boolean sv = signature.getSignatureValue().validate(valContext);
			System.out.println("signature validation status: " + sv);
			// check the validation status of each Reference
			Iterator<?> i = signature.getSignedInfo().getReferences().iterator();
			for (int j = 0; i.hasNext(); j++) {
				boolean refValid = ((Reference) i.next()).validate(valContext);
				System.out.println("ref[" + j + "] validity status: "
						+ refValid);
			}
		} else {
			System.out.println("Signature passed core validation");
		}
//-- added for multiple signature loop
}
	}

	/**
	 * KeySelector which retrieves the public key out of the KeyValue element
	 * and returns it. NOTE: If the key algorithm doesn't match signature
	 * algorithm, then the public key will be ignored.
	 */
	private static class KeyValueKeySelector extends KeySelector {
		public KeySelectorResult select(KeyInfo keyInfo,
				KeySelector.Purpose purpose, AlgorithmMethod method,
				XMLCryptoContext context) throws KeySelectorException {
			
			if (keyInfo == null) {
				throw new KeySelectorException("Null KeyInfo object!");
			}
			SignatureMethod sm = (SignatureMethod) method;
			List<?> list = keyInfo.getContent();

			for (int i = 0; i < list.size(); i++) {
				XMLStructure xmlStructure = (XMLStructure) list.get(i);
				if (xmlStructure instanceof X509Data) {
					PublicKey pk = null;
					List<?> l = ((X509Data) xmlStructure).getContent();
					if (l.size() > 0) {
						X509Certificate cert = (X509Certificate) l.get(0);
						pk = cert.getPublicKey();
//-- added for subject and valid date printing
System.out.println("X509Certificate Subject -> " + cert.getSubjectX500Principal().getName() );
System.out.println("X509Certificate NotAfter -> " + cert.getNotAfter().toString() );
//-- added for SubjectAltName 
try { Collection<List<?>> alternativeNames = cert.getSubjectAlternativeNames();
if ( alternativeNames != null ) {
    for ( List<?> alternativeName : alternativeNames ) {
    	if (  (Integer) alternativeName.get(0) == 0 ) {
    	Object generalName = alternativeName.get(1);
    	if ( generalName instanceof String) {
    		System.out.println(generalName);
    	} else {
    		HexFormat formatHex = HexFormat.ofDelimiter("").withUpperCase();
    		String tmp = new String( formatHex.formatHex((byte[]) generalName));     		   		
    		if ( tmp.indexOf("2A83088C9B5508050501") > 0 ) {	//JPKI OID Common Name 1.2.392.200149.8.5.5.1
    			String tmp1 = new String(Arrays.copyOfRange((byte[]) generalName,18, Array.getLength(generalName)) );
    			System.out.println("署名者名前: " + tmp1) ; 
    		}
    	 	if ( tmp.indexOf("2A83088C9B5508050505") > 0 ) {	//JPKI OID Address 1.2.392.200149.8.5.5.5
    			String tmp1 = new String(Arrays.copyOfRange((byte[]) generalName,18, Array.getLength(generalName)) );
    			System.out.println("署名者住所: " + tmp1) ; 
    		}
    	} // else
    }  else if ( (Integer) alternativeName.get(0) == 4 ) { //-- added for Distinguish Name printing
    	System.out.println(" DN=\"" + (String) alternativeName.get(1) + "\"");
    }
  } // for
} 
} catch (CertificateParsingException e) { System.out.println("CertificateParsing ");}
//-- SubjectAltName end
//-- Validate certification
boolean isValidated;
try {
	String keyStoreFilePath = "/Library/Java/JavaVirtualMachines/jdk-22.jdk/Contents/Home/lib/security/cacerts";
	File keyStoreFile = new File(keyStoreFilePath);
	FileInputStream keyStoreStream = new FileInputStream(keyStoreFile);
	KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
	keyStore.load(keyStoreStream,"changeit".toCharArray());
	PKIXParameters parms = new PKIXParameters(keyStore);
	// parms.setRevocationEnabled(false);
	parms.setPolicyQualifiersRejected(false);
	
	CertPathValidator certValidator = CertPathValidator.getInstance(CertPathValidator.getDefaultType()); // PKIX
	
	PKIXRevocationChecker rc = (PKIXRevocationChecker)certValidator.getRevocationChecker();
	// rc.setOptions(EnumSet.of(Option.SOFT_FAIL));
	parms.addCertPathChecker(rc);
			
	ArrayList<Certificate> start = new ArrayList<>();
    start.add(cert);
    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    CertPath certPath = certFactory.generateCertPath(start);
    certValidator.validate(certPath, parms);
    isValidated = true;
  } catch (KeyStoreException | IOException | NoSuchAlgorithmException | InvalidAlgorithmParameterException | CertificateException | CertPathValidatorException  e) {
	System.out.println("Cannot validate certificate.\r\n	Error is : " + e.getMessage() );
//        System.out.println("Certificate" + cert.toString());
    isValidated = false; // for debuging
}
System.out.println("CertPathValidator with OCSP -> " + isValidated );
//-- Validate certification end

 						if (algEquals(sm.getAlgorithm(), pk.getAlgorithm())) {
							return new SimpleKeySelectorResult(pk);
						}
					}
				}
				if (xmlStructure instanceof KeyValue) {
					PublicKey pk = null;
					try {
						pk = ((KeyValue) xmlStructure).getPublicKey();
					} catch (KeyException ke) {
						throw new KeySelectorException(ke);
					}
					// make sure algorithm is compatible with method
					if (algEquals(sm.getAlgorithm(), pk.getAlgorithm())) {
						return new SimpleKeySelectorResult(pk);
					}
				}
			}
			throw new KeySelectorException("No KeyValue element found!");
		}

		// @@@FIXME: this should also work for key types other than DSA/RSA
		static boolean algEquals(String algURI, String algName ) {
//-- added
System.out.println("Algorithm: " + algURI );
			if (algName.equalsIgnoreCase("DSA")
					&& algURI.equalsIgnoreCase(SignatureMethod.DSA_SHA1)) {
				return true;
			} else if (algName.equalsIgnoreCase("RSA")
					&& algURI.equalsIgnoreCase(SignatureMethod.RSA_SHA256)) {
				return true;
//-- added sha1
			} else if (algName.equalsIgnoreCase("RSA")
					&& algURI.equalsIgnoreCase(SignatureMethod.RSA_SHA1)) {
				return true;
			} else {
				return false;
			}
		}
	}

	private static class SimpleKeySelectorResult implements KeySelectorResult {
		private PublicKey pk;

		SimpleKeySelectorResult(PublicKey pk) {
			this.pk = pk;
		}

		public Key getKey() {
			return pk;
		}
	}
}
信頼する証明書を保存するキーストアファイルのパスは、適宜設定が必要(緑文字部分)。

申請用総合ソフトの公文書
$ java -Djava.util.logging.config.file=./logging.properties -Djava.security.properties=./java.security Validate /Users/someone/Documents/ShinseiyoSogoSoft/申請案件/2/取得公文書/complete_0001/complete_0001.xml 
setBaseURI-> file:///Users/someone/Documents/ShinseiyoSogoSoft/申請案件/2/取得公文書/complete_0001/
Signature block(s) = 1

Signature id = moj.go.jp9999999999999
Find BODY element and setIdAttibute="ID"
X509Certificate Subject -> CN=Registrar99,OU=XXXX Branch Bureau,OU=Nagano District Legal Affairs Bureau,OU=Ministry of Justice,O=Japanese Government,C=JP
X509Certificate NotAfter -> Tue Jan 14 23:59:59 JST 2025
DN="CN=登記官99,OU=XX支局,OU=長野地方法務局,OU=法務省,O=日本国政府,C=JP"
Cannot validate certificate. Error is : Path does not chain with any of the trust anchors
CertPathValidator with OCSP -> false
Algorithm: http://www.w3.org/2001/04/xmldsig-more#rsa-sha256
Signature passed core validation
(一部データを秘匿)

JAVAのキーストアにGPKIのルート証明書が無いのでエラーとなる。GPKIのルート証明書をキーストアにインストールする。
https://www.gpki.go.jp
官職認証局
sudo keytool -importcert -cacerts -noprompt -trustcacerts -alias JP-OFFICIAL-CA -file /Users/someone/Downloads/OSCAroot.der
sudo keytool -importcert -cacerts -noprompt -trustcacerts -alias JP-OFFICIAL-CA1 -file /Users/someone/Downloads/OSCAroot_1.der
sudo keytool -importcert -cacerts -noprompt -trustcacerts -alias JP-OFFICIAL-CA2 -file /Users/someone/Downloads/OSCAroot_2.der
ルート証明書をインストール後、再度検証する
$ java -Djava.util.logging.config.file=./logging.properties -Djava.security.properties=./java.security Validate /Users/someone/Documents/ShinseiyoSogoSoft/申請案件/2/取得公文書/complete_0001/complete_0001.xml 
setBaseURI-> file:///Users/someone/Documents/ShinseiyoSogoSoft/申請案件/2/取得公文書/complete_0001/
Signature block(s) = 1

Signature id = moj.go.jp9999999999999
Find BODY element and setIdAttibute="ID"
X509Certificate Subject -> CN=Registrar99,OU=XXXX Branch Bureau,OU=Nagano District Legal Affairs Bureau,OU=Ministry of Justice,O=Japanese Government,C=JP
X509Certificate NotAfter -> Tue Jan 14 23:59:59 JST 2025
DN="CN=登記官99,OU=XX支局,OU=長野地方法務局,OU=法務省,O=日本国政府,C=JP"
Cannot validate certificate. Error is : Certificate does not specify OCSP responder
CertPathValidator with OCSP -> false
Algorithm: http://www.w3.org/2001/04/xmldsig-more#rsa-sha256
Signature passed core validation
(一部データを秘匿)

署名に使われた証明書は、有効期間内だが失効確認が出来ないためエラーとなる。ルート証明書には、CRLの配布ポイント記載されていない。
CRLの配布ポイントを明示し利用できるようにしてもらいたい。
「申請用総合ソフト」を使用して電子署名の検証をしてみる。証明書の有効性が確認されている。

「申請用総合ソフト」(バージョン:8.4A ( 8.4.1.19 ))の「公文書の検証」では、 公的個人認証の電子署名証明書の有効性確認も可能。
複数人が電子署名したPDFファイルの場合、最初の一人目だけ検証が出来る。
「2番目に署名した者」の検証は、検証対象のフォルダーをコピーし署名ファイルのSignatureブロックをエディターで入れ替えると出来るが手数が掛かる。
2人の署名した署名フォルダ
test1 ---- test1.pdf
        -- test1.xml

コピーした署名フォルダ
test1Copy ---- test1.pdf
            -- test1.xml
「test1Copy/test1.xml」のSignature順番をを入れ替える
<?xml version="1.0" encoding="utf-8"?><PDF署名 version="1.00">
<Signature Id="Signature" xmlns="http://www.w3.org/2000/09/xmldsig#">・・・</Signature>
<Signature Id="Signature1" xmlns="http://www.w3.org/2000/09/xmldsig#">・・・</Signature>
</PDF署名>
から
<?xml version="1.0" encoding="utf-8"?><PDF署名 version="1.00">
<Signature Id="Signature1" xmlns="http://www.w3.org/2000/09/xmldsig#">・・・</Signature>
<Signature Id="Signature" xmlns="http://www.w3.org/2000/09/xmldsig#">・・・</Signature>
</PDF署名>
この署名フォルダ「test1Copy」を検証すると2番目の署名を確認出来る


eTax用の「医療費控除申請用データファイル」(健康保険組合から入手)
$ java -Djava.util.logging.config.file=./logging.properties -Djava.security.properties=./java.security Validate /Volumes/home/確定申告/令和5年度-2023//IK2023999999999900099999_01.xml 
setBaseURI-> file:////Volumes/home/確定申告/令和5年度-2023/
Signature block(s) = 1

Signature id = _99999999999999999999999999999
Find TEG700 element and setIdAttribute="id"
X509Certificate Subject -> CN=Tarou Urashima,OU=SA000000009999,OU=DIACERT Service,O=DIACERT CA,C=JP
X509Certificate NotAfter -> Wed Dec 31 23:59:59 JST 2025
DN="CN=浦島 太郎,2.5.4.97=#0c104a434e39393939393939393939393939,O=健康保険組合,L=新宿区河田町一丁目1番1号,ST=東京都,C=JP"
Cannot validate certificate. 
        Error is: Path does not chain with any of the trust anchors
CertPathValidator with OCSP -> false
Algorithm: http://www.w3.org/2001/04/xmldsig-more#rsa-sha256
Signature passed core validation
(一部データを秘匿)

「DIACERT CA」は、民間ルート証明書だが日本政府公認の「おれおれCA」。OCSPによるCRL配布がされている。
トラスト・キーストアに組み込む
https://www.diacert.jp
sudo keytool -importcert -cacerts -noprompt -trustcacerts -alias DIACERT-CA -file /Users/someone/Downloads/DIACERTCA-G3.cer
$ java -Djava.util.logging.config.file=./logging.properties -Djava.security.properties=./java.security Validate /Volumes/home/確定申告/令和5年度-2023//IK2023999999999900099999_01.xml 
setBaseURI-> file:////Volumes/home/確定申告/令和5年度-2023/
Signature block(s) = 1

Signature id = _99999999999999999999999999999
Find TEG700 element and setIdAttribute="id"
X509Certificate Subject -> CN=Tarou Urashima,OU=SA000000009999,OU=DIACERT Service,O=DIACERT CA,C=JP
X509Certificate NotAfter -> Wed Dec 31 23:59:59 JST 2025
DN="CN=浦島 太郎,2.5.4.97=#0c104a434e39393939393939393939393939,O=健康保険組合,L=新宿区河田町一丁目1番1号,ST=東京都,C=JP"
Cannot validate certificate. 
        Error is: critical policy qualifiers present in certificate
CertPathValidator with OCSP -> false
Algorithm: http://www.w3.org/2001/04/xmldsig-more#rsa-sha256
Signature passed core validation
(一部データを秘匿)

「parms.setPolicyQualifiersRejected(false);」で対応する
$ java -Djava.util.logging.config.file=./logging.properties -Djava.security.properties=./java.security Validate /Volumes/home/確定申告/令和5年度-2023//IK2023999999999900099999_01.xml 
setBaseURI-> file:////Volumes/home/確定申告/令和5年度-2023/
Signature block(s) = 1

Signature id = _99999999999999999999999999999
Find TEG700 element and setIdAttribute="id"
X509Certificate Subject -> CN=Tarou Urashima,OU=SA000000009999,OU=DIACERT Service,O=DIACERT CA,C=JP
X509Certificate NotAfter -> Wed Dec 31 23:59:59 JST 2025
DN="CN=浦島 太郎,2.5.4.97=#0c104a434e39393939393939393939393939,O=健康保険組合,L=新宿区河田町一丁目1番1号,ST=東京都,C=JP"
CertPathValidator with OCSP -> true
Algorithm: http://www.w3.org/2001/04/xmldsig-more#rsa-sha256
Signature passed core validation
(一部データを秘匿)

CRLのディストリビューションポイントへのパケットをキャプチャ確認する


 



 

法務省 不動産登記の電子署名をValidate.javaで検証してみた
法務省 不動産登記の電子署名を確認してみた
法務省 不動産登記の複数人電子署名をValidate.javaで検証してみた
法務省 不動産登記の電子署名用証明書をValidate.javaで検証してみた
 

コメント
  • X
  • Facebookでシェアする
  • はてなブックマークに追加する
  • LINEでシェアする