SecurityUtils.java 96 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274
  1. /*******************************************************************************
  2. * The MIT License (MIT)
  3. *
  4. * Copyright (c) 2015-207 V2G Clarity (Dr.-Ing. Marc Mültin)
  5. *
  6. * Permission is hereby granted, free of charge, to any person obtaining a copy
  7. * of this software and associated documentation files (the "Software"), to deal
  8. * in the Software without restriction, including without limitation the rights
  9. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. * copies of the Software, and to permit persons to whom the Software is
  11. * furnished to do so, subject to the following conditions:
  12. *
  13. * The above copyright notice and this permission notice shall be included in
  14. * all copies or substantial portions of the Software.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. * THE SOFTWARE.
  23. *******************************************************************************/
  24. package com.v2gclarity.risev2g.shared.utils;
  25. import java.io.ByteArrayInputStream;
  26. import java.io.ByteArrayOutputStream;
  27. import java.io.FileInputStream;
  28. import java.io.FileNotFoundException;
  29. import java.io.FileOutputStream;
  30. import java.io.IOException;
  31. import java.io.InputStream;
  32. import java.math.BigInteger;
  33. import java.nio.file.Files;
  34. import java.nio.file.Path;
  35. import java.nio.file.Paths;
  36. import java.security.AlgorithmParameters;
  37. import java.security.InvalidAlgorithmParameterException;
  38. import java.security.InvalidKeyException;
  39. import java.security.Key;
  40. import java.security.KeyFactory;
  41. import java.security.KeyManagementException;
  42. import java.security.KeyPair;
  43. import java.security.KeyPairGenerator;
  44. import java.security.KeyStore;
  45. import java.security.KeyStoreException;
  46. import java.security.MessageDigest;
  47. import java.security.NoSuchAlgorithmException;
  48. import java.security.NoSuchProviderException;
  49. import java.security.PublicKey;
  50. import java.security.SecureRandom;
  51. import java.security.Signature;
  52. import java.security.SignatureException;
  53. import java.security.UnrecoverableKeyException;
  54. import java.security.cert.Certificate;
  55. import java.security.cert.CertificateEncodingException;
  56. import java.security.cert.CertificateException;
  57. import java.security.cert.CertificateExpiredException;
  58. import java.security.cert.CertificateFactory;
  59. import java.security.cert.CertificateNotYetValidException;
  60. import java.security.cert.X509Certificate;
  61. import java.security.interfaces.ECPrivateKey;
  62. import java.security.interfaces.ECPublicKey;
  63. import java.security.spec.ECGenParameterSpec;
  64. import java.security.spec.ECParameterSpec;
  65. import java.security.spec.ECPoint;
  66. import java.security.spec.ECPrivateKeySpec;
  67. import java.security.spec.ECPublicKeySpec;
  68. import java.security.spec.InvalidKeySpecException;
  69. import java.security.spec.InvalidParameterSpecException;
  70. import java.security.spec.PKCS8EncodedKeySpec;
  71. import java.util.ArrayList;
  72. import java.util.Calendar;
  73. import java.util.Date;
  74. import java.util.Enumeration;
  75. import java.util.HashMap;
  76. import java.util.List;
  77. import java.util.concurrent.TimeUnit;
  78. import javax.crypto.BadPaddingException;
  79. import javax.crypto.Cipher;
  80. import javax.crypto.EncryptedPrivateKeyInfo;
  81. import javax.crypto.IllegalBlockSizeException;
  82. import javax.crypto.KeyAgreement;
  83. import javax.crypto.NoSuchPaddingException;
  84. import javax.crypto.SecretKey;
  85. import javax.crypto.SecretKeyFactory;
  86. import javax.crypto.spec.IvParameterSpec;
  87. import javax.crypto.spec.PBEKeySpec;
  88. import javax.crypto.spec.SecretKeySpec;
  89. import javax.naming.InvalidNameException;
  90. import javax.naming.ldap.LdapName;
  91. import javax.naming.ldap.Rdn;
  92. import javax.net.ssl.KeyManager;
  93. import javax.net.ssl.KeyManagerFactory;
  94. import javax.net.ssl.SSLContext;
  95. import javax.net.ssl.TrustManager;
  96. import javax.net.ssl.TrustManagerFactory;
  97. import javax.security.auth.x500.X500Principal;
  98. import javax.xml.bind.JAXBElement;
  99. import org.apache.logging.log4j.LogManager;
  100. import org.apache.logging.log4j.Logger;
  101. import com.v2gclarity.risev2g.shared.enumerations.GlobalValues;
  102. import com.v2gclarity.risev2g.shared.enumerations.PKI;
  103. import com.v2gclarity.risev2g.shared.exiCodec.ExiCodec;
  104. import com.v2gclarity.risev2g.shared.v2gMessages.msgDef.CanonicalizationMethodType;
  105. import com.v2gclarity.risev2g.shared.v2gMessages.msgDef.CertificateChainType;
  106. import com.v2gclarity.risev2g.shared.v2gMessages.msgDef.ContractSignatureEncryptedPrivateKeyType;
  107. import com.v2gclarity.risev2g.shared.v2gMessages.msgDef.DiffieHellmanPublickeyType;
  108. import com.v2gclarity.risev2g.shared.v2gMessages.msgDef.DigestMethodType;
  109. import com.v2gclarity.risev2g.shared.v2gMessages.msgDef.EMAIDType;
  110. import com.v2gclarity.risev2g.shared.v2gMessages.msgDef.ListOfRootCertificateIDsType;
  111. import com.v2gclarity.risev2g.shared.v2gMessages.msgDef.ReferenceType;
  112. import com.v2gclarity.risev2g.shared.v2gMessages.msgDef.ResponseCodeType;
  113. import com.v2gclarity.risev2g.shared.v2gMessages.msgDef.SignatureMethodType;
  114. import com.v2gclarity.risev2g.shared.v2gMessages.msgDef.SignatureType;
  115. import com.v2gclarity.risev2g.shared.v2gMessages.msgDef.SignedInfoType;
  116. import com.v2gclarity.risev2g.shared.v2gMessages.msgDef.SubCertificatesType;
  117. import com.v2gclarity.risev2g.shared.v2gMessages.msgDef.TransformType;
  118. import com.v2gclarity.risev2g.shared.v2gMessages.msgDef.TransformsType;
  119. import com.v2gclarity.risev2g.shared.v2gMessages.msgDef.X509IssuerSerialType;
  120. import java.util.Base64;
  121. public final class SecurityUtils {
  122. /*
  123. * Add VM (virtual machine) argument "-Djavax.net.debug=ssl" if you want more detailed debugging output
  124. */
  125. static Logger logger = LogManager.getLogger(SecurityUtils.class.getSimpleName());
  126. static ExiCodec exiCodec;
  127. static boolean showSignatureVerificationLog = ((boolean) MiscUtils.getPropertyValue("signature.verification.showlog"));
  128. public static enum ContractCertificateStatus {
  129. UPDATE_NEEDED,
  130. INSTALLATION_NEEDED,
  131. OK,
  132. UNKNOWN // is used as default for communication session context
  133. }
  134. public static Logger getLogger() {
  135. return logger;
  136. }
  137. /**
  138. * Returns the standard JKS keystore which holds the respective credentials (private key and
  139. * certificate chain) for the EVCC or SECC (whoever calls this method).
  140. *
  141. * The keystore file itself must reside outside the JAR file, at the same level as the JAR file itself,
  142. * because
  143. * a) at least the evccKeystore needs to be editable when installing the contract certificate (JAR file is read-only), and
  144. * b) it is very likely that private keys and certificate chains might be stored separately in a secure hardware module.
  145. * Therefore, the file is not loaded with getResourceAsStream(), but with a FileInputStream.
  146. *
  147. * @param keyStorePath The relative path and file name of the keystore
  148. * @param keyStorePassword The password which protects the keystore
  149. * @return The respective keystore
  150. */
  151. public static KeyStore getKeyStore(String keyStorePath, String keyStorePassword) {
  152. FileInputStream keyStore;
  153. try {
  154. keyStore = new FileInputStream(keyStorePath);
  155. return getKeyStore(keyStore, keyStorePassword, "jks");
  156. } catch (FileNotFoundException e) {
  157. getLogger().error("Keystore file location '" + keyStorePath + "' not found (FileNotFoundException).");
  158. return null;
  159. }
  160. }
  161. /**
  162. * Returns the standard JKS truststore which holds the respective trusted certificates for the EVCC
  163. * or SECC (whoever calls this method).
  164. *
  165. * The truststore file itself must reside outside the JAR file, at the same level as the JAR file itself,
  166. * because
  167. * a) at least the evccKeystore needs to be editable when installing the contract certificate (JAR file is read-only), and
  168. * b) it is very likely that private keys and certificate chains might be stored separately in a secure hardware module.
  169. * Therefore, the file is not loaded with getResourceAsStream(), but with a FileInputStream.
  170. *
  171. * @param trustStorePath The relative path and file name of the truststore
  172. * @param trustStorePassword The password which protects the truststore
  173. * @return The respective truststore
  174. */
  175. public static KeyStore getTrustStore(String trustStorePath, String trustStorePassword) {
  176. FileInputStream trustStore;
  177. try {
  178. trustStore = new FileInputStream(trustStorePath);
  179. return getKeyStore(trustStore, trustStorePassword, "jks");
  180. } catch (FileNotFoundException e) {
  181. getLogger().error("Truststore file location '" + trustStorePath + "' not found (FileNotFoundException).");
  182. return null;
  183. }
  184. }
  185. /**
  186. * Returns a PKCS#12 container which holds the respective credentials (private key and certificate chain)
  187. *
  188. * @param pkcs12Path The relative path and file name of the PKCS#12 container
  189. * @param password The password which protects the PKCS#12 container
  190. * @return The respective keystore
  191. */
  192. public static KeyStore getPKCS12KeyStore(String pkcs12Path, String password) {
  193. FileInputStream fis = null;
  194. try {
  195. fis = new FileInputStream(pkcs12Path);
  196. return getKeyStore(fis, password, "pkcs12");
  197. } catch (FileNotFoundException e) {
  198. getLogger().error("FileNotFoundException occurred while trying to access PKCS#12 container at " +
  199. "location '" + pkcs12Path + "'");
  200. return null;
  201. }
  202. }
  203. /**
  204. * Returns a standard keystore which holds the respective credentials (private key and certificate chain).
  205. *
  206. * @param keyStoreIS The input stream of the keystore
  207. * @param keyStorePassword The password which protects the keystore
  208. * @param keyStoreType The type of the keystore, either "jks" or "pkcs12"
  209. * @return The respective keystore
  210. */
  211. private static KeyStore getKeyStore(InputStream keyStoreIS, String keyStorePassword, String keyStoreType) {
  212. KeyStore keyStore = null;
  213. try {
  214. keyStore = KeyStore.getInstance(keyStoreType);
  215. keyStore.load(keyStoreIS, keyStorePassword.toCharArray());
  216. keyStoreIS.close();
  217. return keyStore;
  218. } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException |
  219. IOException | NullPointerException e) {
  220. getLogger().error(e.getClass().getSimpleName() + " occurred while trying to load keystore", e);
  221. }
  222. return null;
  223. }
  224. /**
  225. * Checks whether the given certificate is currently valid with regards to date and time.
  226. *
  227. * @param certificate The X509Certificiate to be checked for validity
  228. * @return ResponseCode FAILED_CertificateExpired, if the certificate is expired. FAILED, if the certificate is
  229. * not yet valid, since there is no other proper response code available. OK, otherwise.
  230. */
  231. public static ResponseCodeType verifyValidityPeriod(X509Certificate certificate) {
  232. try {
  233. certificate.checkValidity();
  234. return ResponseCodeType.OK;
  235. } catch (CertificateExpiredException e) {
  236. X500Principal subject = certificate.getSubjectX500Principal();
  237. getLogger().warn("Certificate with distinguished name '" + subject.getName() +
  238. "' already expired (not after " + certificate.getNotAfter() + ")");
  239. return ResponseCodeType.FAILED_CERTIFICATE_EXPIRED;
  240. } catch (CertificateNotYetValidException e) {
  241. X500Principal subject = certificate.getSubjectX500Principal();
  242. getLogger().warn("Certificate with distinguished name '" + subject.getName() +
  243. "' not yet valid (not before " + certificate.getNotBefore() + ")");
  244. return ResponseCodeType.FAILED;
  245. }
  246. }
  247. /**
  248. * Domain Component restrictions: <br/>
  249. * - SECC certificate: "CPO" (verification by EVCC) <br/>
  250. * - CPS leaf certificate: "CPS" (verification by EVCC) <br/>
  251. * - OEM Provisioning Certificate: "OEM" (verification by provisioning service (neither EVCC nor SECC))
  252. *
  253. * @param certificate The X509Certificiate to be checked for validity
  254. * @param domainComponent The domain component to be checked for in the distinguished name of the certificate
  255. * @return True, if the given domain component is present in the distinguished name, false otherwise
  256. */
  257. public static boolean verifyDomainComponent(X509Certificate certificate, String domainComponent) {
  258. String dn = certificate.getSubjectX500Principal().getName();
  259. LdapName ln;
  260. try {
  261. ln = new LdapName(dn);
  262. for (Rdn rdn : ln.getRdns()) {
  263. if (rdn.getType().equalsIgnoreCase("DC") && rdn.getValue().equals(domainComponent)) {
  264. return true;
  265. }
  266. }
  267. } catch (InvalidNameException e) {
  268. getLogger().error("InvalidNameException occurred while trying to check domain component of certificate", e);
  269. }
  270. getLogger().error("Expected domain component (DC) '" + domainComponent + "' not found in certificate "
  271. + "with distinguished name '" + dn + "'");
  272. return false;
  273. }
  274. /**
  275. * Checks how many days a given certificate is still valid.
  276. * If the certificate is not valid any more, a negative number will be returned according to the number
  277. * of days the certificate is already expired.
  278. *
  279. * @param certificate The X509Certificiate to be checked for validity period
  280. * @return The number of days the given certificate is still valid, a negative number if already expired.
  281. */
  282. public static short getValidityPeriod(X509Certificate certificate) {
  283. Date today = Calendar.getInstance().getTime();
  284. Date certificateExpirationDate = certificate.getNotAfter();
  285. long diff = certificateExpirationDate.getTime() - today.getTime();
  286. return (short) TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
  287. }
  288. /**
  289. * Executes the following validity checks:
  290. * <br/><br/>
  291. * 1. Verifies the signature for each certificate in the given certificate chain all the way up to the trust
  292. * anchor. Certificates in certificate chain must be in the right order (leaf -> Sub-CA2 -> Sub-CA1) <br/>
  293. * 2. Verifies whether the given certificate is currently valid with regards to date and time.<br/>
  294. * 3. Verifies that certificate attributes are set correctly, depending on the PKI the certificate chain belongs to
  295. *
  296. * @param certChain The certificate chain to iterate over to check for validity
  297. * @param trustStoreFileName The relative path and file name of the truststore
  298. * @param pki The Public Key Infrastructure to which the certChain belongs (a PKI enumeration value)
  299. * @return ResponseCode applicable to the verification steps
  300. */
  301. public static ResponseCodeType verifyCertificateChain(
  302. CertificateChainType certChain,
  303. String trustStoreFileName,
  304. PKI pki) {
  305. X509Certificate leafCertificate = null;
  306. X509Certificate subCA1Certificate = null;
  307. X509Certificate subCA2Certificate = null;
  308. ResponseCodeType responseCode = null;
  309. // Get leaf certificate
  310. if (certChain != null) {
  311. leafCertificate = getCertificate(certChain.getCertificate());
  312. } else {
  313. getLogger().error("Signature verification failed because provided certificate chain is empty (null)");
  314. return ResponseCodeType.FAILED_CERT_CHAIN_ERROR;
  315. }
  316. // Get Sub-CA certificates
  317. if (leafCertificate != null) {
  318. SubCertificatesType subCertificates = certChain.getSubCertificates();
  319. if (subCertificates != null && subCertificates.getCertificate().size() != 0) {
  320. subCA2Certificate = getCertificate(subCertificates.getCertificate().get(0));
  321. if (subCertificates.getCertificate().size() == 2)
  322. subCA1Certificate = getCertificate(subCertificates.getCertificate().get(1));
  323. } else {
  324. getLogger().error("Signature verification failed because no Sub-CA certificates available in provided "
  325. + "certificate chain");
  326. return ResponseCodeType.FAILED_CERT_CHAIN_ERROR;
  327. }
  328. } else {
  329. getLogger().error("Signature verification failed because no leaf certificate available in provided "
  330. + "certificate chain");
  331. return ResponseCodeType.FAILED_CERT_CHAIN_ERROR;
  332. }
  333. /*
  334. * ****************
  335. * SIGNATURE CHECKS
  336. * ****************
  337. */
  338. // Check signature of leaf certificate
  339. if (!verifySignature(leafCertificate, subCA2Certificate)) return ResponseCodeType.FAILED_CERT_CHAIN_ERROR;
  340. // Check signature of Sub-CA 2 and optionally, if present, Sub-CA 2 certificate
  341. if (subCA1Certificate != null) {
  342. if (!verifySignature(subCA2Certificate, subCA1Certificate)) return ResponseCodeType.FAILED_CERT_CHAIN_ERROR;
  343. if (!verifySignature(subCA1Certificate, trustStoreFileName)) return ResponseCodeType.FAILED_CERT_CHAIN_ERROR;
  344. } else {
  345. // In case there is only one intermediate certificate (profile of Sub-CA 2)
  346. if (!verifySignature(subCA2Certificate, trustStoreFileName)) return ResponseCodeType.FAILED_CERT_CHAIN_ERROR;
  347. }
  348. /*
  349. * **********************
  350. * VALIDITY PERIOD CHECKS
  351. * **********************
  352. */
  353. ResponseCodeType validityResponseCode = null;
  354. // Check validity of leaf certificate
  355. validityResponseCode = verifyValidityPeriod(leafCertificate);
  356. if (!validityResponseCode.equals(ResponseCodeType.OK)) return validityResponseCode;
  357. // Check validity of Sub-CA2 certificate
  358. validityResponseCode = verifyValidityPeriod(subCA2Certificate);
  359. if (!validityResponseCode.equals(ResponseCodeType.OK)) return validityResponseCode;
  360. // Check validity of Sub-CA1 certificate, if present
  361. if (subCA1Certificate != null) {
  362. validityResponseCode = verifyValidityPeriod(subCA1Certificate);
  363. if (!validityResponseCode.equals(ResponseCodeType.OK)) return validityResponseCode;
  364. }
  365. /*
  366. * ***********************************
  367. * COMMON CERTIFICATE ATTRIBUTES CHECK
  368. * ***********************************
  369. */
  370. // Check pathLenContraint (maximum number of non-self-issued intermediate certificates that may follow this certificate)
  371. if (subCA2Certificate.getBasicConstraints() != 0) {
  372. getLogger().error("Sub-CA 2 certificate with distinguished name '" +
  373. subCA2Certificate.getSubjectX500Principal().getName() + "' has incorrect value for " +
  374. "pathLenConstraint. Should be 0 instead of " + subCA2Certificate.getBasicConstraints());
  375. return ResponseCodeType.FAILED_CERTIFICATE_EXPIRED;
  376. }
  377. if (subCA1Certificate != null && subCA1Certificate.getBasicConstraints() != 1) {
  378. getLogger().error("Sub-CA 1 certificate with distinguished name '" +
  379. subCA1Certificate.getSubjectX500Principal().getName() + "' has incorrect value for " +
  380. "pathLenConstraint. Should be 1 instead of " + subCA2Certificate.getBasicConstraints());
  381. return ResponseCodeType.FAILED_CERTIFICATE_EXPIRED;
  382. }
  383. responseCode = verifyLeafCertificateAttributes(leafCertificate, pki);
  384. if (responseCode.equals(ResponseCodeType.OK))
  385. return responseCode;
  386. return ResponseCodeType.OK;
  387. }
  388. /**
  389. * Checks certificate attributes for a given leaf certificate belonging to an ISO 15118 PKI.
  390. *
  391. * @param certificate The X.509 certificate whose attributes need to be checked
  392. * @param pki The PKI to which the certificate belongs
  393. * @return
  394. */
  395. public static ResponseCodeType verifyLeafCertificateAttributes(X509Certificate leafCertificate, PKI pki) {
  396. switch (pki) {
  397. case CPO:
  398. if (!verifyDomainComponent(leafCertificate, "CPO")) {
  399. getLogger().error("SECC leaf certificate with distinguished name '" +
  400. leafCertificate.getSubjectX500Principal().getName() + "' has incorrect value for " +
  401. "domain component. Should be 'CPO'");
  402. return ResponseCodeType.FAILED_CERT_CHAIN_ERROR;
  403. }
  404. break;
  405. case CPS:
  406. if (!verifyDomainComponent(leafCertificate, "CPS")) {
  407. getLogger().error("CPS leaf certificate with distinguished name '" +
  408. leafCertificate.getSubjectX500Principal().getName() + "' has incorrect value for " +
  409. "domain component. Should be 'CPS'");
  410. return ResponseCodeType.FAILED_CERT_CHAIN_ERROR;
  411. }
  412. break;
  413. case MO:
  414. if (!isEMAIDSyntaxValid(leafCertificate)) {
  415. return ResponseCodeType.FAILED_CERT_CHAIN_ERROR;
  416. }
  417. break;
  418. case OEM:
  419. if (!verifyDomainComponent(leafCertificate, "OEM")) {
  420. getLogger().error("OEM provisioning certificate with distinguished name '" +
  421. leafCertificate.getSubjectX500Principal().getName() + "' has incorrect value for " +
  422. "domain component. Should be 'OEM'");
  423. return ResponseCodeType.FAILED_CERT_CHAIN_ERROR;
  424. }
  425. break;
  426. default:
  427. break;
  428. }
  429. return ResponseCodeType.OK;
  430. }
  431. /**
  432. * Verifies that the given certificate was signed using the private key that corresponds to the
  433. * public key of the provided certificate.
  434. *
  435. * @param certificate The X509Certificate which is to be checked
  436. * @param issuingCertificate The X.509 certificate which holds the public key corresponding to the private
  437. * key with which the given certificate should have been signed
  438. * @return True, if the verification was successful, false otherwise
  439. */
  440. public static boolean verifySignature(X509Certificate certificate, X509Certificate issuingCertificate) {
  441. X500Principal subject = certificate.getSubjectX500Principal();
  442. X500Principal expectedIssuerSubject = certificate.getIssuerX500Principal();
  443. X500Principal issuerSubject = issuingCertificate.getSubjectX500Principal();
  444. PublicKey publicKeyForSignature = issuingCertificate.getPublicKey();
  445. try {
  446. certificate.verify(publicKeyForSignature);
  447. return true;
  448. } catch (InvalidKeyException | CertificateException | NoSuchAlgorithmException |
  449. NoSuchProviderException | SignatureException e) {
  450. getLogger().warn("\n"
  451. + "\tSignature verification of certificate having distinguished name \n"
  452. + "\t'" + subject.getName() + "'\n"
  453. + "\twith certificate having distinguished name (the issuer) \n"
  454. + "\t'" + issuerSubject.getName() + "'\n"
  455. + "\tfailed. Expected issuer has distinguished name \n"
  456. + "\t'" + expectedIssuerSubject.getName() + "' (" + e.getClass().getSimpleName() + ")", e);
  457. }
  458. return false;
  459. }
  460. /**
  461. * Iterates over the certificates stored in the truststore to verify the signature of the provided certificate
  462. *
  463. * @param trustStoreFilename The relative path and file name of the truststore
  464. * @param certificate The certificate whose signature needs to be signed
  465. * @return True, if the provided certificate has been signed by one of the certificates in the
  466. * truststore, false otherwise
  467. */
  468. public static boolean verifySignature(X509Certificate certificate, String trustStoreFilename) {
  469. KeyStore trustStore = SecurityUtils.getTrustStore(trustStoreFilename, GlobalValues.PASSPHRASE_FOR_CERTIFICATES_AND_KEYS.toString());
  470. X500Principal expectedIssuer = certificate.getIssuerX500Principal();
  471. try {
  472. Enumeration<String> aliases = trustStore.aliases();
  473. while (aliases.hasMoreElements()) {
  474. X509Certificate rootCA = (X509Certificate) trustStore.getCertificate(aliases.nextElement());
  475. if (rootCA.getSubjectX500Principal().getName().equals(expectedIssuer.getName()) &&
  476. verifySignature(certificate, rootCA)) return true;
  477. }
  478. } catch (KeyStoreException | NullPointerException e) {
  479. getLogger().error(e.getClass().getSimpleName() + " occurred while trying to verify trust " +
  480. "status of certificate with distinguished name '" +
  481. certificate.getSubjectX500Principal().getName() + "' with truststore at " +
  482. "location '" + trustStoreFilename + "'", e);
  483. }
  484. return false;
  485. }
  486. /**
  487. * Returns the leaf certificate from a given certificate chain.
  488. *
  489. * @param certChain The certificate chain given as an array of Certificate instances
  490. * @return The leaf certificate (begin not a CA)
  491. */
  492. public static X509Certificate getLeafCertificate(Certificate[] certChain) {
  493. for (Certificate cert : certChain) {
  494. X509Certificate x509Cert = (X509Certificate) cert;
  495. // Check whether the pathLen constraint is set which indicates if this certificate is a CA
  496. if (x509Cert.getBasicConstraints() == -1) return x509Cert;
  497. }
  498. getLogger().warn("No leaf certificate found in given certificate chain");
  499. return null;
  500. }
  501. /**
  502. * Returns the intermediate certificates (sub CAs) from a given certificate chain.
  503. *
  504. * @param certChain The certificate chain given as an array of Certificate instances
  505. * @return The sub certificates given as a list of byte arrays contained in a SubCertiticatesType instance
  506. */
  507. public static SubCertificatesType getSubCertificates(Certificate[] certChain) {
  508. SubCertificatesType subCertificates = new SubCertificatesType();
  509. for (Certificate cert : certChain) {
  510. X509Certificate x509Cert = (X509Certificate) cert;
  511. // Check whether the pathLen constraint is set which indicates if this certificate is a CA
  512. if (x509Cert.getBasicConstraints() != -1)
  513. try {
  514. subCertificates.getCertificate().add(x509Cert.getEncoded());
  515. } catch (CertificateEncodingException e) {
  516. X500Principal subject = x509Cert.getIssuerX500Principal();
  517. getLogger().error("A CertificateEncodingException occurred while trying to get certificate " +
  518. "with distinguished name '" + subject.getName().toString() + "'", e);
  519. }
  520. }
  521. if (subCertificates.getCertificate().size() == 0) {
  522. getLogger().warn("No intermediate CAs found in given certificate array");
  523. }
  524. return subCertificates;
  525. }
  526. /**
  527. * Returns the list of X509IssuerSerialType instances of the root CAs contained in the truststore.
  528. *
  529. * @param trustStoreFileName The relative path and file name of the truststore
  530. * @param trustStorePassword The password which protects the truststore
  531. * @return The list of X509IssuerSerialType instances of the root CAs
  532. */
  533. public static ListOfRootCertificateIDsType getListOfRootCertificateIDs(
  534. String trustStoreFileName,
  535. String trustStorePassword) {
  536. KeyStore evccTrustStore = getTrustStore(trustStoreFileName, trustStorePassword);
  537. ListOfRootCertificateIDsType rootCertificateIDs = new ListOfRootCertificateIDsType();
  538. X509Certificate cert = null;
  539. try {
  540. Enumeration<String> aliases = evccTrustStore.aliases();
  541. while (aliases.hasMoreElements()) {
  542. cert = (X509Certificate) evccTrustStore.getCertificate(aliases.nextElement());
  543. X509IssuerSerialType serialType = new X509IssuerSerialType();
  544. serialType.setX509IssuerName(cert.getIssuerX500Principal().getName());
  545. serialType.setX509SerialNumber(cert.getSerialNumber());
  546. rootCertificateIDs.getRootCertificateID().add(serialType);
  547. }
  548. } catch (KeyStoreException | NullPointerException e) {
  549. getLogger().error(e.getClass().getSimpleName() + " occurred while trying to get list of " +
  550. "root certificate IDs from truststore at location '" + trustStoreFileName + "'", e);
  551. }
  552. return rootCertificateIDs;
  553. }
  554. /**
  555. * Returns an instance of a X.509 certificate created from its raw byte array
  556. *
  557. * @param certificate The byte array representing a X.509 certificate
  558. * @return The X.509 certificate
  559. */
  560. public static X509Certificate getCertificate(byte[] certificate) {
  561. X509Certificate cert = null;
  562. try {
  563. InputStream in = new ByteArrayInputStream(certificate);
  564. CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
  565. cert = (X509Certificate) certFactory.generateCertificate(in);
  566. } catch (CertificateException e) {
  567. getLogger().error("CertificateException occurred when trying to create X.509 certificate from byte array", e);
  568. }
  569. return cert;
  570. }
  571. /**
  572. * Returns the mobility operator Sub-CA 2 certificate (MOSubCA2 certificate) which can verify the signature of the
  573. * contract certificate from the given keystore. The public key of the MOSub2Certificate is then used to verify
  574. * the signature of sales tariffs.
  575. *
  576. * @param keyStoreFileName The relative path and file name of the keystore
  577. * @return The X.509 mobility operator Sub-CA2 certificate (a certificate from a Sub-CA)
  578. */
  579. public static X509Certificate getMOSubCA2Certificate(String keyStoreFileName) {
  580. KeyStore keystore = getKeyStore(keyStoreFileName, GlobalValues.PASSPHRASE_FOR_CERTIFICATES_AND_KEYS.toString());
  581. X509Certificate moSubCA2Certificate = null;
  582. try {
  583. Certificate[] certChain = keystore.getCertificateChain(GlobalValues.ALIAS_CONTRACT_CERTIFICATE.toString());
  584. X509Certificate contractCertificate = getLeafCertificate(certChain);
  585. SubCertificatesType subCertificates = getSubCertificates(certChain);
  586. for (byte[] certificate : subCertificates.getCertificate()) {
  587. X509Certificate x509Cert = getCertificate(certificate);
  588. if (contractCertificate.getIssuerX500Principal().getName().equals(
  589. x509Cert.getSubjectX500Principal().getName())) {
  590. moSubCA2Certificate = x509Cert;
  591. break;
  592. }
  593. }
  594. } catch (KeyStoreException e) {
  595. getLogger().error("KeyStoreException occurred while trying to get MOSubCA2 certificate");
  596. }
  597. return moSubCA2Certificate;
  598. }
  599. /**
  600. * Returns the ECPublicKey instance from its encoded raw bytes.
  601. * The first byte has the fixed value 0x04 indicating the uncompressed form.
  602. * Therefore, the byte array must be of form: [0x04, x coord of point (32 bytes), y coord of point (32 bytes)]
  603. *
  604. * @param publicKeyBytes The byte array representing the encoded raw bytes of the public key
  605. * @return The ECPublicKey instance
  606. */
  607. public static ECPublicKey getPublicKey(byte[] publicKeyBytes) {
  608. // First we separate x and y of coordinates into separate variables
  609. byte[] x = new byte[32];
  610. byte[] y = new byte[32];
  611. System.arraycopy(publicKeyBytes, 1, x, 0, 32);
  612. System.arraycopy(publicKeyBytes, 33, y, 0, 32);
  613. try {
  614. KeyFactory kf = KeyFactory.getInstance("EC");
  615. AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC");
  616. parameters.init(new ECGenParameterSpec("secp256r1"));
  617. ECParameterSpec ecParameterSpec = parameters.getParameterSpec(ECParameterSpec.class);
  618. ECPublicKeySpec ecPublicKeySpec = new ECPublicKeySpec(new ECPoint(new BigInteger(x), new BigInteger(y)), ecParameterSpec);
  619. ECPublicKey ecPublicKey = (ECPublicKey) kf.generatePublic(ecPublicKeySpec);
  620. return ecPublicKey;
  621. } catch (NoSuchAlgorithmException | InvalidParameterSpecException | InvalidKeySpecException e) {
  622. getLogger().error(e.getClass().getSimpleName() + " occurred when trying to get public key from raw bytes", e);
  623. return null;
  624. }
  625. }
  626. /**
  627. * Returns the public key part of an elliptic curve Diffie-Hellman keypair
  628. *
  629. * @param ecdhKeyPair The elliptic curve Diffie-Hellman keypair
  630. * @return The respective public key
  631. */
  632. public static DiffieHellmanPublickeyType getDHPublicKey(KeyPair ecdhKeyPair) {
  633. DiffieHellmanPublickeyType dhPublicKey = new DiffieHellmanPublickeyType();
  634. /*
  635. * Experience from the test symposium in San Diego (April 2016):
  636. * The Id element of the signature is not restricted in size by the standard itself. But on embedded
  637. * systems, the memory is very limited which is why we should not use long IDs for the signature reference
  638. * element. A good size would be 3 characters max (like the example in the ISO 15118-2 annex J)
  639. */
  640. dhPublicKey.setId("id1");
  641. byte[] uncompressedDHpublicKey = getUncompressedSubjectPublicKey((ECPublicKey) ecdhKeyPair.getPublic());
  642. getLogger().debug("Created DHpublickey: " + ByteUtils.toHexString(uncompressedDHpublicKey));
  643. dhPublicKey.setValue(uncompressedDHpublicKey);
  644. return dhPublicKey;
  645. }
  646. /**
  647. * Returns the ECPrivateKey instance from its raw bytes. Note that you must provide the "s" value of the
  648. * private key, not e.g. the byte array from reading a PKCS#8 key file.
  649. *
  650. * @param privateKeyBytes The byte array (the "s" value) of the private key
  651. * @return The ECPrivateKey instance
  652. */
  653. public static ECPrivateKey getPrivateKey(byte[] privateKeyBytes) {
  654. try {
  655. AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC");
  656. parameters.init(new ECGenParameterSpec("secp256r1"));
  657. ECParameterSpec ecParameterSpec = parameters.getParameterSpec(ECParameterSpec.class);
  658. ECPrivateKeySpec ecPrivateKeySpec = new ECPrivateKeySpec(new BigInteger(privateKeyBytes), ecParameterSpec);
  659. ECPrivateKey privateKey = (ECPrivateKey) KeyFactory.getInstance("EC").generatePrivate(ecPrivateKeySpec);
  660. return privateKey;
  661. } catch (NoSuchAlgorithmException | InvalidKeySpecException | InvalidParameterSpecException e) {
  662. getLogger().error(e.getClass().getSimpleName() + " occurred when trying to get private key from raw bytes", e);
  663. return null;
  664. }
  665. }
  666. /**
  667. * Searches the given keystore for the private key. It is assumed that the given keystore holds
  668. * only one private key entry whose alias is not known before, which is the case during certificate
  669. * installation when the SECC uses a PKCS#12 container encapsulating the
  670. * contract certificate, its private key and an optional chain of intermediate CAs.
  671. *
  672. * @param keyStore The PKCS#12 keystore
  673. * @return The private key contained in the given keystore as an ECPrivateKey
  674. */
  675. public static ECPrivateKey getPrivateKey(KeyStore keyStore) {
  676. ECPrivateKey privateKey = null;
  677. try {
  678. Enumeration<String> aliases = keyStore.aliases();
  679. // Only one certificate chain (and therefore alias) should be available
  680. while (aliases.hasMoreElements()) {
  681. privateKey = (ECPrivateKey) keyStore.getKey(
  682. aliases.nextElement(),
  683. GlobalValues.PASSPHRASE_FOR_CERTIFICATES_AND_KEYS.toString().toCharArray());
  684. }
  685. } catch (KeyStoreException | UnrecoverableKeyException | NoSuchAlgorithmException |
  686. NullPointerException e) {
  687. getLogger().error(e.getClass().getSimpleName() + " occurred while trying to get private " +
  688. "key from keystore", e);
  689. }
  690. return privateKey;
  691. }
  692. /**
  693. * Reads the private key from an encrypted PKCS#8 file and returns it as an ECPrivateKey instance.
  694. *
  695. * @param A PKCS#8 (.key) file containing the private key with value "s"
  696. * @return The private key as an ECPrivateKey instance
  697. */
  698. public static ECPrivateKey getPrivateKey(String keyFilePath) {
  699. Path fileLocation = Paths.get(keyFilePath);
  700. byte[] pkcs8ByteArray;
  701. try {
  702. pkcs8ByteArray = Files.readAllBytes(fileLocation);
  703. // The DER encoded private key is password-based encrypted and provided in PKCS#8. So we need to decrypt it first
  704. PBEKeySpec pbeKeySpec = new PBEKeySpec(GlobalValues.PASSPHRASE_FOR_CERTIFICATES_AND_KEYS.toString().toCharArray());
  705. EncryptedPrivateKeyInfo encryptedPrivKeyInfo = new EncryptedPrivateKeyInfo(pkcs8ByteArray);
  706. SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(encryptedPrivKeyInfo.getAlgName());
  707. Key secret = secretKeyFactory.generateSecret(pbeKeySpec);
  708. PKCS8EncodedKeySpec pkcs8PrivKeySpec = encryptedPrivKeyInfo.getKeySpec(secret);
  709. ECPrivateKey privateKey = (ECPrivateKey) KeyFactory.getInstance("EC").generatePrivate(pkcs8PrivKeySpec);
  710. return privateKey;
  711. } catch (IOException | InvalidKeySpecException | NoSuchAlgorithmException | InvalidKeyException e) {
  712. getLogger().error(e.getClass().getSimpleName() + " occurred while trying to access private key at " +
  713. "location '" + keyFilePath + "'");
  714. return null;
  715. }
  716. }
  717. /**
  718. * Searches the given keystore for the private key which corresponds to the provided alias.
  719. * Example: In case of the EVCC and during certificate installation, the private key of the
  720. * OEM provisioning certificate is needed. During certificate update, the private key of the
  721. * existing contract certificate is needed.
  722. *
  723. * @param keyStore The keystore of EVCC or SECC
  724. * @param alias The alias of a specific private key entry
  725. * @return The private key corresponding to the respective alias in the given keystore
  726. */
  727. public static ECPrivateKey getPrivateKey(KeyStore keyStore, String alias) {
  728. ECPrivateKey privateKey = null;
  729. try {
  730. privateKey = (ECPrivateKey) keyStore.getKey(
  731. alias,
  732. GlobalValues.PASSPHRASE_FOR_CERTIFICATES_AND_KEYS.toString().toCharArray());
  733. } catch (KeyStoreException | UnrecoverableKeyException | NoSuchAlgorithmException e) {
  734. getLogger().error("The private key from keystore with alias '" + alias +
  735. "' could not be retrieved (" + e.getClass().getSimpleName() + ")", e);
  736. }
  737. return privateKey;
  738. }
  739. /**
  740. * Returns the SecretKey instance from its raw bytes
  741. *
  742. * @param key The byte array representing the symmetric SecretKey instance
  743. * @return The SecretKey instance
  744. */
  745. public static SecretKey getSecretKey(byte[] key) {
  746. SecretKey secretKey = new SecretKeySpec(key, 0, key.length, "DiffieHellman");
  747. return secretKey;
  748. }
  749. /**
  750. * Returns the certificate chain from a PKCS#12 container holding credentials such as private key,
  751. * leaf certificate and zero or more intermediate certificates.
  752. *
  753. * @param pkcs12Resource The PKCS#12 container
  754. * @return The certificate chain
  755. */
  756. public static CertificateChainType getCertificateChain(String pkcs12Resource) {
  757. CertificateChainType certChain = new CertificateChainType();
  758. /*
  759. * For testing purposes, the respective PKCS12 container file has already been put in the
  760. * resources folder. However, when implementing a real interface to a secondary actor's backend,
  761. * the retrieval of a certificate must be done via some other online mechanism.
  762. */
  763. KeyStore contractCertificateKeystore = getPKCS12KeyStore(pkcs12Resource, GlobalValues.PASSPHRASE_FOR_CERTIFICATES_AND_KEYS.toString());
  764. if (contractCertificateKeystore == null) {
  765. getLogger().error("Unable to access certificate chain because no PKCS#12 container found at " +
  766. "location '" + pkcs12Resource + "'");
  767. return null;
  768. }
  769. try {
  770. Enumeration<String> aliases = contractCertificateKeystore.aliases();
  771. Certificate[] tempCertChain = null;
  772. // Only one certificate chain (and therefore alias) should be available
  773. while (aliases.hasMoreElements()) {
  774. tempCertChain = contractCertificateKeystore.getCertificateChain(aliases.nextElement());
  775. certChain.setCertificate(getLeafCertificate(tempCertChain).getEncoded());
  776. certChain.setSubCertificates(getSubCertificates(tempCertChain));
  777. }
  778. } catch (KeyStoreException | CertificateEncodingException | NullPointerException e) {
  779. getLogger().error(e.getClass().getSimpleName() + " occurred while trying to get " +
  780. "certificate chain from resource '" + pkcs12Resource + "'", e);
  781. }
  782. return certChain;
  783. }
  784. /**
  785. * Returns the SignedInfo element of the V2GMessage header, based on the provided HashMap which holds
  786. * the reference IDs (URIs) and the corresponding SHA-256 digests.
  787. *
  788. * @param xmlSignatureRefElements A HashMap of Strings (reflecting the reference IDs) and digest values
  789. * @return The SignedInfoType instance
  790. */
  791. public static SignedInfoType getSignedInfo(HashMap<String, byte[]> xmlSignatureRefElements) {
  792. /*
  793. * According to requirement [V2G2-771] in ISO/IEC 15118-2 the following message elements of the
  794. * XML signature framework shall not be used:
  795. * - Id (attribute in SignedInfo)
  796. * - ##any in SignedInfo – CanonicalizationMethod
  797. * - HMACOutputLength in SignedInfo – SignatureMethod
  798. * - ##other in SignedInfo – SignatureMethod
  799. * - Type (attribute in SignedInfo-Reference)
  800. * - ##other in SignedInfo – Reference – Transforms – Transform
  801. * - XPath in SignedInfo – Reference – Transforms – Transform
  802. * - ##other in SignedInfo – Reference – DigestMethod
  803. * - Id (attribute in SignatureValue)
  804. * - Object (in Signature)
  805. * - KeyInfo
  806. */
  807. DigestMethodType digestMethod = new DigestMethodType();
  808. digestMethod.setAlgorithm("http://www.w3.org/2001/04/xmlenc#sha256");
  809. TransformType transform = new TransformType();
  810. transform.setAlgorithm("http://www.w3.org/TR/canonical-exi/");
  811. TransformsType transforms = new TransformsType();
  812. transforms.getTransform().add(transform);
  813. List<ReferenceType> references = new ArrayList<ReferenceType>();
  814. xmlSignatureRefElements.forEach( (k,v) -> {
  815. ReferenceType reference = new ReferenceType();
  816. reference.setDigestMethod(digestMethod);
  817. reference.setDigestValue(v);
  818. reference.setTransforms(transforms);
  819. reference.setURI("#" + k);
  820. references.add(reference);
  821. });
  822. CanonicalizationMethodType canonicalizationMethod = new CanonicalizationMethodType();
  823. canonicalizationMethod.setAlgorithm("http://www.w3.org/TR/canonical-exi/");
  824. SignatureMethodType signatureMethod = new SignatureMethodType();
  825. signatureMethod.setAlgorithm("http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256");
  826. SignedInfoType signedInfo = new SignedInfoType();
  827. signedInfo.setCanonicalizationMethod(canonicalizationMethod);
  828. signedInfo.setSignatureMethod(signatureMethod);
  829. signedInfo.getReference().addAll(references);
  830. return signedInfo;
  831. }
  832. /**
  833. * Saves the newly received contract certificate chain, provided by CertificateInstallationRes or
  834. * CertificateUpdateRes.
  835. *
  836. * @param keyStorePassword The password which protects the EVCC keystore
  837. * @param contractCertChain The certificate chain belonging to the contract certificate
  838. * @param contractCertPrivateKey The private key corresponding to the public key of the leaf certificate
  839. * stored in the certificate chain
  840. * @return True, if the contract certificate chain and private key could be saved, false otherwise
  841. */
  842. public static boolean saveContractCertificateChain(
  843. String keyStorePassword,
  844. CertificateChainType contractCertChain,
  845. ECPrivateKey contractCertPrivateKey) {
  846. KeyStore keyStore = getKeyStore(GlobalValues.EVCC_KEYSTORE_FILEPATH.toString(), keyStorePassword);
  847. try {
  848. if (isPrivateKeyValid(contractCertPrivateKey, contractCertChain)) {
  849. keyStore.setKeyEntry(
  850. GlobalValues.ALIAS_CONTRACT_CERTIFICATE.toString(),
  851. contractCertPrivateKey,
  852. keyStorePassword.toCharArray(),
  853. getCertificateChain(contractCertChain));
  854. // Save the keystore persistently
  855. FileOutputStream fos = new FileOutputStream("evccKeystore.jks");
  856. keyStore.store(fos, GlobalValues.PASSPHRASE_FOR_CERTIFICATES_AND_KEYS.toString().toCharArray());
  857. fos.close();
  858. X509Certificate contractCert = getCertificate(contractCertChain.getCertificate());
  859. getLogger().info("Contract certificate with distinguished name '" +
  860. contractCert.getSubjectX500Principal().getName() + "' saved. " +
  861. "Valid until " + contractCert.getNotAfter()
  862. );
  863. getLogger().debug("Decrypted private key belonging to contract certificate saved. Key bytes: " +
  864. ByteUtils.toHexString(contractCertPrivateKey.getEncoded()));
  865. } else {
  866. getLogger().error("Private key for contract certificate is not valid");
  867. return false;
  868. }
  869. } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException | NullPointerException e) {
  870. getLogger().error(e.getClass().getSimpleName() + " occurred while trying to save contract " +
  871. "certificate chain", e);
  872. return false;
  873. }
  874. return true;
  875. }
  876. /**
  877. * Checks if the private key is a valid key (according to requirement [V2G2-823]) for the received contract
  878. * certificate before saving it to the keystore.
  879. * @param privateKey The private key corresponding to the contract certificate
  880. * @param contractCertChain The received contract certificate chain
  881. * @return True, if the private key is a valid key, false otherwise.
  882. */
  883. private static boolean isPrivateKeyValid(ECPrivateKey privateKey, CertificateChainType contractCertChain) {
  884. AlgorithmParameters parameters;
  885. try {
  886. parameters = AlgorithmParameters.getInstance("EC");
  887. parameters.init(new ECGenParameterSpec("secp256r1"));
  888. ECParameterSpec ecParameterSpec = parameters.getParameterSpec(ECParameterSpec.class);
  889. // Now we need to check if the private key is correct (see requirement [V2G2-823])
  890. BigInteger order = ecParameterSpec.getOrder();
  891. ECPoint basePoint = ecParameterSpec.getGenerator();
  892. BigInteger privateKeyValue = privateKey.getS();
  893. X509Certificate contractCert = getCertificate(contractCertChain.getCertificate());
  894. ECPublicKey publicKey = (ECPublicKey) contractCert.getPublicKey();
  895. // 1. check
  896. if (privateKeyValue.compareTo(order) != -1) {
  897. getLogger().error("Validation of private key failed: its value is not strictly smaller than the "
  898. + "order of the base point");
  899. return false;
  900. }
  901. // 2. check
  902. /*
  903. * TODO:
  904. * No idea how to check for
  905. * "multiplication of the base point with this value must generate a key matching the public key of
  906. * the contract certificate"
  907. * "this value" = value of private key
  908. * -> some more expert knowledge on the arithmetic of elliptic curves is needed to tackle this!
  909. */
  910. } catch (NoSuchAlgorithmException | InvalidParameterSpecException e) {
  911. getLogger().error(e.getClass().getSimpleName() + " occurred when trying to get private key from raw bytes", e);
  912. return false;
  913. }
  914. return true;
  915. }
  916. /**
  917. * Gets the contract certificate from the EVCC keystore.
  918. *
  919. * @return The contract certificate if present, null otherwise
  920. */
  921. public static X509Certificate getContractCertificate() {
  922. X509Certificate contractCertificate = null;
  923. KeyStore evccKeyStore = getKeyStore(
  924. GlobalValues.EVCC_KEYSTORE_FILEPATH.toString(),
  925. GlobalValues.PASSPHRASE_FOR_CERTIFICATES_AND_KEYS.toString()
  926. );
  927. try {
  928. contractCertificate = (X509Certificate) evccKeyStore.getCertificate(GlobalValues.ALIAS_CONTRACT_CERTIFICATE.toString());
  929. } catch (KeyStoreException e) {
  930. getLogger().error("KeyStoreException occurred while trying to get contract certificate from keystore", e);
  931. }
  932. return contractCertificate;
  933. }
  934. /**
  935. * A convenience function which checks if a contract certificate installation is needed.
  936. * Normally not needed because of function getContractCertificateStatus().
  937. *
  938. * @return True, if no contract certificate is store or if the stored certificate is not valid, false otherwise
  939. */
  940. public static boolean isContractCertificateInstallationNeeded() {
  941. X509Certificate contractCert = getContractCertificate();
  942. if (contractCert == null) {
  943. getLogger().info("No contract certificate stored");
  944. return true;
  945. } else if (!verifyValidityPeriod(contractCert).equals(ResponseCodeType.OK)) {
  946. return true;
  947. } else return false;
  948. }
  949. /**
  950. * A convenience function which checks if a contract certificate update is needed.
  951. * Normally not needed because of function getContractCertificateStatus().
  952. *
  953. * @return True, if contract certificate is still valid but about to expire, false otherwise.
  954. * The expiration period is given in GlobalValues.CERTIFICATE_EXPIRES_SOON_PERIOD.
  955. */
  956. public static boolean isContractCertificateUpdateNeeded() {
  957. X509Certificate contractCert = getContractCertificate();
  958. short validityOfContractCert = getValidityPeriod(contractCert);
  959. if (validityOfContractCert < 0) {
  960. getLogger().warn("Contract certificate with distinguished name '" +
  961. contractCert.getSubjectX500Principal().getName() + "' is not valid any more, expired " +
  962. Math.abs(validityOfContractCert) + " days ago");
  963. return false;
  964. } else if (validityOfContractCert <= GlobalValues.CERTIFICATE_EXPIRES_SOON_PERIOD.getShortValue()) {
  965. getLogger().info("Contract certificate with distinguished name '" +
  966. contractCert.getSubjectX500Principal().getName() + "' is about to expire in " +
  967. validityOfContractCert + " days");
  968. return true;
  969. } else return false;
  970. }
  971. /**
  972. * Checks whether a contract certificate
  973. * - is stored
  974. * - in case it is stored, if it is valid
  975. * - in case it is valid, if it expires soon
  976. *
  977. * This method is intended to reduce cryptographic computation overhead by checking both, if installation or
  978. * update is needed, at the same time. When executing either method by itself (isContractCertificateUpdateNeeded() and
  979. * isContractCertificateInstallationNeeded()), each time the certificate is read anew from the Java keystore
  980. * holding the contract certificate. With this method the contract certificate is read just once from the keystore.
  981. *
  982. * @return An enumeration value ContractCertificateStatus (either UPDATE_NEEDED, INSTALLATION_NEEDED, or OK)
  983. */
  984. public static ContractCertificateStatus getContractCertificateStatus() {
  985. X509Certificate contractCert = getContractCertificate();
  986. if (contractCert == null) {
  987. getLogger().info("No contract certificate stored");
  988. return ContractCertificateStatus.INSTALLATION_NEEDED;
  989. } else if (contractCert != null && !verifyValidityPeriod(contractCert).equals(ResponseCodeType.OK)) {
  990. return ContractCertificateStatus.INSTALLATION_NEEDED;
  991. } else {
  992. short validityOfContractCert = getValidityPeriod(contractCert);
  993. // Checking for a negative value of validityOfContractCert is not needed because the method
  994. // isCertificateValid() already checks for that
  995. if (validityOfContractCert <= GlobalValues.CERTIFICATE_EXPIRES_SOON_PERIOD.getShortValue()) {
  996. getLogger().info("Contract certificate with distinguished name '" +
  997. contractCert.getSubjectX500Principal().getName() + "' is about to expire in " +
  998. validityOfContractCert + " days");
  999. return ContractCertificateStatus.UPDATE_NEEDED;
  1000. }
  1001. return ContractCertificateStatus.OK;
  1002. }
  1003. }
  1004. /**
  1005. * Returns a list of certificates from the given CertificateChainType with the leaf certificate
  1006. * being the first element and potential subcertificates (intermediate CA certificatess)
  1007. * in the array of certificates.
  1008. *
  1009. * @param certChainType The CertificateChainType instance which holds a leaf certificate and
  1010. * possible intermediate certificates to verify the leaf certificate up to
  1011. * some root certificate.
  1012. * @return An array of Certificates
  1013. */
  1014. public static Certificate[] getCertificateChain(CertificateChainType certChainType) {
  1015. List<byte[]> subCertificates = certChainType.getSubCertificates().getCertificate();
  1016. Certificate[] certChain = new Certificate[subCertificates.size() + 1];
  1017. certChain[0] = getCertificate(certChainType.getCertificate());
  1018. for (int i = 0; i < subCertificates.size(); i++) {
  1019. certChain[i+1] = getCertificate(subCertificates.get(i));
  1020. }
  1021. return certChain;
  1022. }
  1023. /**
  1024. * Generates an elliptic curve key pair using the named curve "secp256r1".
  1025. * This function is mainly used for the ECDH procedure.
  1026. *
  1027. * To use ECC (elliptic curve cryptography), SECC as well as EVCC must agree on all the elements
  1028. * defining the elliptic curve, that is, the "domain parameters" of the scheme. Such domain
  1029. * parameters are predefined by standardization bodies and are commonly known as "standard curves"
  1030. * or "named curves"; a named curve can be referenced either by name or by the unique object
  1031. * identifier defined in the standard documents. For the ISO/IEC 15118-2 document, the named curve
  1032. * "secp256r1" (SECG notation, see http://www.secg.org/sec2-v2.pdf) is used.
  1033. * See [V2G2-818] in ISO/IEC 15118-2 for further information.
  1034. *
  1035. * @return An elliptic curve key pair according to the named curve 'secp256r1'
  1036. */
  1037. public static KeyPair getECKeyPair() {
  1038. KeyPair keyPair = null;
  1039. try {
  1040. KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC");
  1041. ECGenParameterSpec ecParameterSpec = new ECGenParameterSpec("secp256r1");
  1042. keyPairGenerator.initialize(ecParameterSpec, new SecureRandom());
  1043. keyPair = keyPairGenerator.generateKeyPair();
  1044. } catch (InvalidAlgorithmParameterException | NoSuchAlgorithmException e) {
  1045. getLogger().error(e.getClass().getSimpleName() + " occurred while trying to generate ECDH key pair", e);
  1046. }
  1047. return keyPair;
  1048. }
  1049. /**
  1050. * The shared secret is computed using the domain parameters of the named curve "secp256r1", the private key
  1051. * part of the ephemeral key pair, and the OEM provisioning certiicate’s public key (in case of certificate
  1052. * installation) or the contract certificate's public key (in case of certificate update).
  1053. * The shared secret is used as input to a key derivation function.
  1054. * A key derivation function (KDF) is a deterministic algorithm to derive a key of a given
  1055. * size from some secret value. If two parties use the same shared secret value and the same KDF,
  1056. * they should always derive exactly the same key.
  1057. *
  1058. * @param privateKey The private key of an EC key pair generated from the named curve "secp256r1".
  1059. *
  1060. * The mobility operator (MO) provides his ephemeral private key when using this function for
  1061. * generating the shared secret to encrypt the private key of the contract certificate.
  1062. *
  1063. * The EVCC provides the private key belonging to his OEM provisioning certificate's public key
  1064. * when using this function for generating the shared secret to decrypt the encrypted private key
  1065. * of the newly to be installed contract certificate.
  1066. * @param publicKey The public key of an EC key pair generated from the named curve "secp256r1"
  1067. *
  1068. * The mobility operator (MO) provides the static OEM provisioning certificate's (in case of
  1069. * CertificateInstallation) or old contract certificate's (in case of CertificateUpdate)
  1070. * public key when using this function for generating the shared secret to encrypt the private
  1071. * key of the contract certificate.
  1072. *
  1073. * The EVCC provides the ephemeral public key of the MO (coming with the CertificateInstallationRes
  1074. * or CertificateUpdateRes, respectively) when using this function for generating the shared secret
  1075. * to decrypt the encrypted private key of the newly to be installed contract certificate.
  1076. * @return The computed shared secret of the elliptic curve Diffie-Hellman key exchange protocol
  1077. */
  1078. public static byte[] generateSharedSecret(ECPrivateKey privateKey, ECPublicKey publicKey) {
  1079. try {
  1080. KeyAgreement keyAgreement = KeyAgreement.getInstance("ECDH");
  1081. keyAgreement.init(privateKey, new SecureRandom());
  1082. keyAgreement.doPhase(publicKey, true);
  1083. return keyAgreement.generateSecret();
  1084. } catch (InvalidKeyException | NoSuchAlgorithmException e) {
  1085. getLogger().error(e.getClass().getSimpleName() + " occurred while trying to generate the shared secret (ECDH)", e);
  1086. return null;
  1087. }
  1088. }
  1089. /**
  1090. * The key derivation function (KDF). See [V2G2-818] in ISO/IEC 15118-2 for further information.
  1091. *
  1092. * @param sharedSecret The shared secret derived from the ECDH algorithm
  1093. */
  1094. public static SecretKey generateSessionKey(byte[] sharedSecret) {
  1095. MessageDigest md = null;
  1096. /*
  1097. * TODO it is unclear to me what should be the content of suppPubInfo or suppPrivInfo
  1098. * according to page 49 of http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-56Ar2.pdf
  1099. * Requirement [V2G2-818] is not clear about that.
  1100. */
  1101. byte[] suppPubInfo = null;
  1102. byte[] suppPrivInfo = null;
  1103. try {
  1104. md = MessageDigest.getInstance("SHA-256");
  1105. } catch (NoSuchAlgorithmException e1) {
  1106. getLogger().error("Message digest algorithm SHA-256 not supported");
  1107. return null;
  1108. }
  1109. ByteArrayOutputStream baosOtherInfo = new ByteArrayOutputStream();
  1110. try {
  1111. baosOtherInfo.write(ByteUtils.toByteArrayFromHexString("01")); // algorithm ID
  1112. baosOtherInfo.write(ByteUtils.toByteArrayFromHexString("55")); // partyUInfo
  1113. baosOtherInfo.write(ByteUtils.toByteArrayFromHexString("56")); // partyVInfo
  1114. if (suppPubInfo != null) baosOtherInfo.write(suppPubInfo);
  1115. if (suppPrivInfo != null) baosOtherInfo.write(suppPrivInfo);
  1116. } catch (IOException e) {
  1117. getLogger().error("IOException occurred while trying to write OtherInfo for session key generation", e);
  1118. }
  1119. byte[] otherInfo = baosOtherInfo.toByteArray();
  1120. // A symmetric encryption key of exactly 128 bits shall be derived.
  1121. byte[] sessionKeyAsByteArray = concatKDF(md, sharedSecret, 128, otherInfo);
  1122. SecretKey sessionKey = null;
  1123. try {
  1124. sessionKey = new SecretKeySpec(sessionKeyAsByteArray, "AES");
  1125. } catch (IllegalArgumentException e) {
  1126. getLogger().error("IllegalArgumentException occurred while trying to generate session key", e);
  1127. }
  1128. return sessionKey;
  1129. }
  1130. /**
  1131. * Implementation of Concatenation Key Derivation Function
  1132. * http://csrc.nist.gov/publications/nistpubs/800-56A/SP800-56A_Revision1_Mar08-2007.pdf
  1133. *
  1134. * Author: NimbusDS Lai Xin Chu and Vladimir Dzhuvinov
  1135. *
  1136. * See https://code.google.com/p/openinfocard/source/browse/trunk/testsrc/org/xmldap/crypto/ConcatKeyDerivationFunction.java?r=770
  1137. */
  1138. private static byte[] concatKDF(MessageDigest md, byte[] z, int keyDataLen, byte[] otherInfo) {
  1139. final long MAX_HASH_INPUTLEN = Long.MAX_VALUE;
  1140. final long UNSIGNED_INT_MAX_VALUE = 4294967295L;
  1141. keyDataLen = keyDataLen/8;
  1142. byte[] key = new byte[keyDataLen];
  1143. int hashLen = md.getDigestLength();
  1144. int reps = keyDataLen / hashLen;
  1145. if (reps > UNSIGNED_INT_MAX_VALUE) {
  1146. getLogger().error("Key derivation failed");
  1147. return null;
  1148. }
  1149. int counter = 1;
  1150. byte[] counterInBytes = ByteUtils.intToFourBytes(counter);
  1151. if ((counterInBytes.length + z.length + otherInfo.length) * 8 > MAX_HASH_INPUTLEN) {
  1152. getLogger().error("Key derivation failed");
  1153. return null;
  1154. }
  1155. for (int i = 0; i <= reps; i++) {
  1156. md.reset();
  1157. md.update(ByteUtils.intToFourBytes(i+1));
  1158. md.update(z);
  1159. md.update(otherInfo);
  1160. byte[] hash = md.digest();
  1161. if (i < reps) {
  1162. System.arraycopy(hash, 0, key, hashLen * i, hashLen);
  1163. } else {
  1164. if (keyDataLen % hashLen == 0) {
  1165. System.arraycopy(hash, 0, key, hashLen * i, hashLen);
  1166. } else {
  1167. System.arraycopy(hash, 0, key, hashLen * i, keyDataLen % hashLen);
  1168. }
  1169. }
  1170. }
  1171. return key;
  1172. }
  1173. private static ContractSignatureEncryptedPrivateKeyType getContractSignatureEncryptedPrivateKey(
  1174. SecretKey sessionKey, ECPrivateKey contractCertPrivateKey) {
  1175. ContractSignatureEncryptedPrivateKeyType encryptedPrivateKey = new ContractSignatureEncryptedPrivateKeyType();
  1176. encryptedPrivateKey.setValue(encryptPrivateKey(sessionKey, contractCertPrivateKey));
  1177. return encryptedPrivateKey;
  1178. }
  1179. /**
  1180. * Encrypts the private key of the contract certificate which is to be sent to the EVCC. First, the
  1181. * shared secret based on the ECDH parameters is calculated, then the symmetric session key with which
  1182. * the private key of the contract certificate is to be encrypted.
  1183. *
  1184. * @param certificateECPublicKey The public key of either the OEM provisioning certificate (in case of
  1185. * CertificateInstallation) or the to be updated contract certificate
  1186. * (in case of CertificateUpdate)
  1187. * @param dhPrivateKey The DH private key
  1188. * @param contractCertPrivateKey The private key of the contract certificate
  1189. * @return The encrypted private key of the to be installed contract certificate
  1190. */
  1191. public static ContractSignatureEncryptedPrivateKeyType encryptContractCertPrivateKey(
  1192. ECPublicKey certificateECPublicKey,
  1193. ECPrivateKey dhPrivateKey,
  1194. ECPrivateKey contractCertPrivateKey) {
  1195. // Generate the shared secret by using the public key of either OEMProvCert or ContractCert
  1196. byte[] sharedSecret = generateSharedSecret(dhPrivateKey, certificateECPublicKey);
  1197. if (sharedSecret == null) {
  1198. getLogger().error("Shared secret could not be generated");
  1199. return null;
  1200. }
  1201. // The session key is generated using the computed shared secret
  1202. SecretKey sessionKey = generateSessionKey(sharedSecret);
  1203. // Finally, the private key of the contract certificate is encrypted using the session key
  1204. ContractSignatureEncryptedPrivateKeyType encryptedContractCertPrivateKey =
  1205. getContractSignatureEncryptedPrivateKey(sessionKey, contractCertPrivateKey);
  1206. return encryptedContractCertPrivateKey;
  1207. }
  1208. /**
  1209. * Applies the algorithm AES-CBC-128 according to NIST Special Publication 800-38A.
  1210. * The initialization vector IV shall be randomly generated before encryption and shall have a
  1211. * length of 128 bit and never be reused.
  1212. * The IV shall be transmitted in the 16 most significant bytes of the
  1213. * ContractSignatureEncryptedPrivateKey field.
  1214. *
  1215. * @param sessionKey The symmetric session key with which the private key will be encrypted
  1216. * @param contractCertPrivateKey The private key which is to be encrypted
  1217. * @return The encrypted private key of the contract certificate given as a byte array
  1218. */
  1219. private static byte[] encryptPrivateKey(SecretKey sessionKey, ECPrivateKey contractCertPrivateKey) {
  1220. try {
  1221. /*
  1222. * Padding of the plain text (private key) is not required as its length (256 bit) is a
  1223. * multiple of the block size (128 bit) of the used encryption algorithm (AES)
  1224. */
  1225. Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
  1226. IvParameterSpec ivParamSpec = new IvParameterSpec(generateRandomNumber(16));
  1227. cipher.init(Cipher.ENCRYPT_MODE, sessionKey, ivParamSpec);
  1228. /*
  1229. * Not the complete ECPrivateKey container, but the private value s represents the 256 bit
  1230. * private key which must be encoded.
  1231. * The private key is stored as an ASN.1 integer which may need to have zero padding
  1232. * in the most significant bits removed (if 33 bytes)
  1233. */
  1234. byte[] encryptedKey;
  1235. if (contractCertPrivateKey.getS().toByteArray().length == 33) {
  1236. byte[] temp = new byte[32];
  1237. System.arraycopy(contractCertPrivateKey.getS().toByteArray(), 1, temp, 0, contractCertPrivateKey.getS().toByteArray().length-1);
  1238. encryptedKey = cipher.doFinal(temp);
  1239. } else {
  1240. encryptedKey = cipher.doFinal(contractCertPrivateKey.getS().toByteArray());
  1241. }
  1242. /*
  1243. * The IV must be transmitted in the 16 most significant bytes of the
  1244. * ContractSignatureEncryptedPrivateKey
  1245. */
  1246. byte[] encryptedKeyWithIV = new byte[ivParamSpec.getIV().length + encryptedKey.length];
  1247. System.arraycopy(ivParamSpec.getIV(), 0, encryptedKeyWithIV, 0, ivParamSpec.getIV().length);
  1248. System.arraycopy(encryptedKey, 0, encryptedKeyWithIV, ivParamSpec.getIV().length, encryptedKey.length);
  1249. getLogger().debug("Encrypted private key: " + ByteUtils.toHexString(encryptedKeyWithIV));
  1250. return encryptedKeyWithIV;
  1251. } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException |
  1252. InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) {
  1253. getLogger().error(e.getClass().getSimpleName() + " occurred while trying to encrypt private key." +
  1254. "\nSession key (" + sessionKey.getEncoded().length + " bytes): " +
  1255. ByteUtils.toHexString(sessionKey.getEncoded()) +
  1256. "\nContract certificate private key (" + contractCertPrivateKey.getS().toByteArray().length + " bytes): " +
  1257. ByteUtils.toHexString(contractCertPrivateKey.getS().toByteArray()), e);
  1258. }
  1259. return null;
  1260. }
  1261. /**
  1262. * Decrypts the encrypted private key of the contract certificate which is to be installed.
  1263. *
  1264. * @param dhPublicKey The ECDH public key received the the respective response message
  1265. * (either CertificateInstallationRes or CertificateUpdateRes)
  1266. * @param contractSignatureEncryptedPrivateKey The encrypted private key of the contract certificate
  1267. * @param certificateECPrivateKey The private key of either OEMProvisioningCertificate (in case of
  1268. * receipt of CertificateInstallationRes) or the existing ContractCertificate which is to be
  1269. * updated (in case of receipt of CertificateUpdateRes).
  1270. * @return The decrypted private key of the contract certificate which is to be installed
  1271. */
  1272. public static ECPrivateKey decryptContractCertPrivateKey(
  1273. byte[] dhPublicKey,
  1274. byte[] contractSignatureEncryptedPrivateKey,
  1275. ECPrivateKey certificateECPrivateKey) {
  1276. // Generate shared secret
  1277. ECPublicKey publicKey = getPublicKey(dhPublicKey);
  1278. byte[] sharedSecret = generateSharedSecret(certificateECPrivateKey, publicKey);
  1279. if (sharedSecret == null) {
  1280. getLogger().error("Shared secret could not be generated");
  1281. return null;
  1282. }
  1283. // Generate the session key ...
  1284. SecretKey sessionKey = generateSessionKey(sharedSecret);
  1285. if (sessionKey == null) {
  1286. getLogger().error("Session key secret could not be generated");
  1287. return null;
  1288. }
  1289. // ... to decrypt the contract certificate private key
  1290. ECPrivateKey contractCertPrivateKey = decryptPrivateKey(sessionKey, contractSignatureEncryptedPrivateKey);
  1291. if (contractCertPrivateKey == null) {
  1292. getLogger().error("Contract certificate private key secret could not be decrypted");
  1293. return null;
  1294. }
  1295. return contractCertPrivateKey;
  1296. }
  1297. /**
  1298. * The private key corresponding to the contract certificate is to be decrypted by
  1299. * the receiver (EVCC) using the session key derived in the ECDH protocol.
  1300. * Applies the algorithm AES-CBC-128 according to NIST Special Publication 800-38A.
  1301. * The initialization vector IV shall be read from the 16 most significant bytes of the
  1302. * ContractSignatureEncryptedPrivateKey field.
  1303. *
  1304. * @param sessionKey The symmetric session key with which the encrypted private key is to be decrypted
  1305. * @param encryptedKeyWithIV The encrypted private key of the contract certificate given as a byte array
  1306. * whose first 16 byte hold the initialization vector
  1307. * @return The decrypted private key of the contract certificate
  1308. */
  1309. private static ECPrivateKey decryptPrivateKey(SecretKey sessionKey, byte[] encryptedKeyWithIV) {
  1310. byte[] initVector = new byte[16];
  1311. byte[] encryptedKey = null;
  1312. try {
  1313. // Get the first 16 bytes of the encrypted private key which hold the IV
  1314. encryptedKey = new byte[encryptedKeyWithIV.length - 16];
  1315. System.arraycopy(encryptedKeyWithIV, 0, initVector, 0, 16);
  1316. System.arraycopy(encryptedKeyWithIV, 16, encryptedKey, 0, encryptedKeyWithIV.length - 16);
  1317. IvParameterSpec ivParamSpec = new IvParameterSpec(initVector);
  1318. Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
  1319. /*
  1320. * You must have the Java Cryptography Extension (JCE) Unlimited Strength
  1321. * Jurisdiction Policy Files 8 installed, otherwise this cipher.init call will yield a
  1322. * "java.security.InvalidKeyException: Illegal key size"
  1323. */
  1324. cipher.init(Cipher.DECRYPT_MODE, sessionKey, ivParamSpec);
  1325. byte[] decrypted = cipher.doFinal(encryptedKey);
  1326. return getPrivateKey(decrypted);
  1327. } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException |
  1328. InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException |
  1329. NegativeArraySizeException e) {
  1330. getLogger().error(e.getClass().getSimpleName() + " occurred while trying to decrypt private key" +
  1331. "\nSession key (" + (sessionKey != null ? sessionKey.getEncoded().length : 0) + " bytes): " +
  1332. ByteUtils.toHexString(sessionKey.getEncoded()) +
  1333. "\nEncrypted key (" + (encryptedKey != null ? encryptedKey.length : 0) + " bytes): " +
  1334. ByteUtils.toHexString(encryptedKey) +
  1335. "\nEncrypted key with IV (" + (encryptedKeyWithIV != null ? encryptedKeyWithIV.length : 0) + " bytes): " +
  1336. ByteUtils.toHexString(encryptedKey), e);
  1337. }
  1338. return null;
  1339. }
  1340. /**
  1341. * Useful for debugging purposes when verifying a signature and trying to figure out where it went wrong if
  1342. * a signature verification failed.
  1343. *
  1344. * @return
  1345. */
  1346. // public static byte[] decryptSignature(byte[] signature, ECPublicKey publicKey) {
  1347. //
  1348. // }
  1349. /**
  1350. * Returns the EMAID (e-mobility account identifier) from the contract certificate as part of the contract certificate chain.
  1351. *
  1352. * @param contractCertificateChain The certificate chain holding the contract certificate
  1353. * @return The EMAID
  1354. */
  1355. public static EMAIDType getEMAID(CertificateChainType contractCertificateChain) {
  1356. X509Certificate contractCertificate = getCertificate(contractCertificateChain.getCertificate());
  1357. return getEMAIDFromDistinguishedName(contractCertificate.getSubjectX500Principal().getName());
  1358. }
  1359. /**
  1360. * Returns the EMAID (e-mobility account identifier) from the contract certificate.
  1361. *
  1362. * @param contractCertificate The contract certificate
  1363. * @return The EMAID
  1364. */
  1365. public static EMAIDType getEMAID(X509Certificate contractCertificate) {
  1366. return getEMAIDFromDistinguishedName(contractCertificate.getSubjectX500Principal().getName());
  1367. }
  1368. /**
  1369. * Returns the EMAID (e-mobility account identifier) from the contract certificate.
  1370. *
  1371. * @param keyStorePassword The password which protects the keystore holding the contract certificate
  1372. * @return The EMAID
  1373. */
  1374. public static EMAIDType getEMAID(String keyStorePassword) {
  1375. KeyStore keyStore = getKeyStore(GlobalValues.EVCC_KEYSTORE_FILEPATH.toString(), keyStorePassword);
  1376. try {
  1377. X509Certificate contractCertificate =
  1378. (X509Certificate) keyStore.getCertificate(GlobalValues.ALIAS_CONTRACT_CERTIFICATE.toString());
  1379. if (contractCertificate == null) {
  1380. getLogger().error("No contract certificate with alias '" +
  1381. GlobalValues.ALIAS_CONTRACT_CERTIFICATE.toString() + "' found");
  1382. return null;
  1383. }
  1384. return getEMAIDFromDistinguishedName(contractCertificate.getSubjectX500Principal().getName());
  1385. } catch (KeyStoreException e) {
  1386. getLogger().error("KeyStoreException occurred while trying to get EMAID from keystore", e);
  1387. return null;
  1388. }
  1389. }
  1390. /**
  1391. * Reads the EMAID (e-mobility account identifier) from the distinguished name (DN) of a certificate.
  1392. *
  1393. * @param distinguishedName The distinguished name whose 'CN' component holds the EMAID
  1394. * @return The EMAID
  1395. */
  1396. private static EMAIDType getEMAIDFromDistinguishedName(String distinguishedName) {
  1397. EMAIDType emaid = new EMAIDType();
  1398. LdapName ln = null;
  1399. try {
  1400. ln = new LdapName(distinguishedName);
  1401. } catch (InvalidNameException e) {
  1402. getLogger().error("InvalidNameException occurred while trying to get EMAID from distinguished name", e);
  1403. }
  1404. for(Rdn rdn : ln.getRdns()) {
  1405. if (rdn.getType().equalsIgnoreCase("CN")) {
  1406. // Optional hyphens used for better human readability must be omitted here
  1407. emaid.setId("id1");
  1408. emaid.setValue(rdn.getValue().toString().replace("-", ""));
  1409. break;
  1410. }
  1411. }
  1412. return emaid;
  1413. }
  1414. /**
  1415. * Searches a given keystore either for a contract certificate chain or OEM provisioning certificate
  1416. * chain, determined by the alias (the alias is associated with the certificate chain and the private
  1417. * key).
  1418. * However, it may be the case that more than once contract certificate is installed in the EV,
  1419. * in which case an OEM specific implementation would need to interact at this point with a HMI in
  1420. * order to enable the user to select the certificate which is to be used for contract based charging.
  1421. *
  1422. * @param evccKeyStore The keystore to check for the respective certificate chain
  1423. * @param alias The alias associated with a key entry and certificate chain
  1424. * @return The respective certificate chain if present, null otherwise
  1425. */
  1426. public static CertificateChainType getCertificateChain(KeyStore evccKeyStore, String alias) {
  1427. CertificateChainType certChain = new CertificateChainType();
  1428. SubCertificatesType subCertificates = new SubCertificatesType();
  1429. try {
  1430. Certificate[] certChainArray = evccKeyStore.getCertificateChain(alias);
  1431. if (certChainArray == null) {
  1432. getLogger().info("No certificate chain found for alias '" + alias + "'");
  1433. return null;
  1434. }
  1435. certChain.setCertificate(certChainArray[0].getEncoded());
  1436. for (int i = 1; i < certChainArray.length; i++) {
  1437. subCertificates.getCertificate().add(certChainArray[i].getEncoded());
  1438. }
  1439. certChain.setSubCertificates(subCertificates);
  1440. return certChain;
  1441. } catch (KeyStoreException | CertificateEncodingException e) {
  1442. getLogger().error(e.getClass().getSimpleName() + " occurred while trying to get certificate chain", e);
  1443. return null;
  1444. }
  1445. }
  1446. /**
  1447. * Returns a random number of a given length of bytes.
  1448. *
  1449. * @param lengthOfBytes The number of bytes which hold the generated random number
  1450. * @return A random number given as a byte array
  1451. */
  1452. public static byte[] generateRandomNumber(int lengthOfBytes) {
  1453. // TODO how to assure that the entropy of the genChallenge is at least 120 bits according to [V2G2-826]?
  1454. SecureRandom random = new SecureRandom();
  1455. byte[] randomNumber = new byte[lengthOfBytes];
  1456. random.nextBytes(randomNumber);
  1457. return randomNumber;
  1458. }
  1459. /**
  1460. * Generates a digest for a complete message or field (which ever is handed over as first parameter).
  1461. * During digest (SHA-256) generation, the parameter is converted to a JAXBElement and then EXI encoded
  1462. * using the respective EXI schema-informed grammar. If the digest for the signature is to be generated,
  1463. * the second parameter is to be set to true, for all other messages or fields the second parameter
  1464. * needs to be set to false.
  1465. *
  1466. * @param jaxbMessageOrField The message or field for which a digest is to be generated, given as a JAXB element
  1467. * @param digestForSignedInfoElement True if a digest for the SignedInfoElement of the header's signature is to be generated, false otherwise
  1468. * @return The SHA-256 digest for message or field
  1469. */
  1470. @SuppressWarnings("rawtypes")
  1471. public static byte[] generateDigest(String id, JAXBElement jaxbMessageOrField) {
  1472. byte[] encoded;
  1473. // The schema-informed fragment grammar option needs to be used for EXI encodings in the header's signature
  1474. getExiCodec().setFragment(true);
  1475. /*
  1476. * When creating the signature value for the SignedInfoElement, we need to use the XMLdsig schema,
  1477. * whereas for creating the reference elements of the signature, we need to use the V2G_CI_MsgDef schema.
  1478. */
  1479. if (jaxbMessageOrField.getValue() instanceof SignedInfoType) {
  1480. encoded = getExiCodec().encodeEXI(jaxbMessageOrField, GlobalValues.SCHEMA_PATH_XMLDSIG.toString());
  1481. } else encoded = getExiCodec().encodeEXI(jaxbMessageOrField, GlobalValues.SCHEMA_PATH_MSG_DEF.toString());
  1482. // Do not use the schema-informed fragment grammar option for other EXI encodings (message bodies)
  1483. getExiCodec().setFragment(false);
  1484. if (encoded == null) {
  1485. getLogger().error("Digest could not be generated because of EXI encoding problem");
  1486. return null;
  1487. }
  1488. try {
  1489. MessageDigest md = MessageDigest.getInstance("SHA-256");
  1490. md.update(encoded);
  1491. byte[] digest = md.digest();
  1492. if (showSignatureVerificationLog) {
  1493. /*
  1494. * Show Base64 encoding of digests only for reference elements, not for the SignedInfo element.
  1495. * The hashed SignedInfo element is input for ECDSA before the final signature value gets Base64 encoded.
  1496. */
  1497. if ( !(jaxbMessageOrField.getValue() instanceof SignedInfoType) ) {
  1498. getLogger().debug("\n"
  1499. + "\tDigest generated for XML reference element " + jaxbMessageOrField.getName().getLocalPart() + " with ID '" + id + "': " + ByteUtils.toHexString(digest) + "\n"
  1500. + "\tBase64 encoding of digest: " + Base64.getEncoder().encodeToString(digest));
  1501. }
  1502. }
  1503. return digest;
  1504. } catch (NoSuchAlgorithmException e) {
  1505. getLogger().error("NoSuchAlgorithmException occurred while trying to create digest", e);
  1506. return null;
  1507. }
  1508. }
  1509. /**
  1510. * Signs the SignedInfo element of the V2GMessage header.
  1511. *
  1512. * @param signedInfoElementExi The EXI-encoded SignedInfo element given as a byte array
  1513. * @param ecPrivateKey The private key which is used to sign the SignedInfo element
  1514. * @return The signature value for the SignedInfo element given as a byte array
  1515. */
  1516. public static byte[] signSignedInfoElement(byte[] signedInfoElementExi, ECPrivateKey ecPrivateKey) {
  1517. try {
  1518. Signature ecdsa = Signature.getInstance("SHA256withECDSA", "SunEC");
  1519. getLogger().debug("EXI encoded SignedInfo: " + ByteUtils.toHexString(signedInfoElementExi));
  1520. if (ecPrivateKey != null) {
  1521. getLogger().debug("\n\tPrivate key used for creating signature: " + ByteUtils.toHexString(ecPrivateKey.getS().toByteArray()));
  1522. ecdsa.initSign(ecPrivateKey);
  1523. ecdsa.update(signedInfoElementExi);
  1524. byte[] signature = ecdsa.sign();
  1525. // Java operates on DER encoded signatures, but we must send the raw r and s values as signature
  1526. byte[] rawSignature = getRawSignatureFromDEREncoding(signature);
  1527. getLogger().debug("Signature value: " + ByteUtils.toHexString(rawSignature));
  1528. return rawSignature;
  1529. } else {
  1530. getLogger().error("Private key used to sign SignedInfo element is null");
  1531. return null;
  1532. }
  1533. } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException | NoSuchProviderException e) {
  1534. getLogger().error(e.getClass().getSimpleName() + " occurred while trying to create signature", e);
  1535. return null;
  1536. }
  1537. }
  1538. /**
  1539. * Verifies the signature given in the received header of an EVCC or SECC message
  1540. *
  1541. * @param signature The received header's signature
  1542. * @param jaxbSignature The received header's signature, given as a JAXB element (needed for EXI operations)
  1543. * @param verifyXMLSigRefElements The HashMap of signature IDs and digest values of the message body
  1544. * or fields respectively of the received message (to cross-check against the XML reference
  1545. * elements contained in the received message header)
  1546. * @param verifyCert The certificate holding the public key corresponding to the private key which was used
  1547. * for the signature. Given as a byte array, this function will call verifySignature() with an X509Certificate
  1548. * as last parameter.
  1549. * @return True, if digest validation of all XML reference elements and signature validation was
  1550. * successful, false otherwise
  1551. */
  1552. public static boolean verifySignature(
  1553. SignatureType signature,
  1554. JAXBElement<SignedInfoType> jaxbSignature,
  1555. HashMap<String, byte[]> verifyXMLSigRefElements,
  1556. byte[] verifyCert) {
  1557. X509Certificate x509VerifyCert = getCertificate(verifyCert);
  1558. return verifySignature(signature, jaxbSignature, verifyXMLSigRefElements, x509VerifyCert);
  1559. }
  1560. /**
  1561. * Verifies the signature given in the received header of an EVCC or SECC message
  1562. *
  1563. * @param signature The received header's signature
  1564. * @param jaxbSignature The received header's signature, given as a JAXB element (needed for EXI operations)
  1565. * @param verifyXMLSigRefElements The HashMap of signature IDs and digest values of the message body
  1566. * or fields respectively of the received message (to cross-check against the XML reference
  1567. * elements contained in the received message header)
  1568. * @param verifyCert The certificate holding the public key corresponding to the private key which was used for the signature
  1569. * @return True, if digest validation of all XML reference elements and signature validation was
  1570. * successful, false otherwise
  1571. */
  1572. public static boolean verifySignature(
  1573. SignatureType signature,
  1574. JAXBElement<SignedInfoType> jaxbSignedInfo,
  1575. HashMap<String, byte[]> verifyXMLSigRefElements,
  1576. X509Certificate verifyCert) {
  1577. byte[] calculatedReferenceDigest;
  1578. boolean messageDigestsEqual;
  1579. /*
  1580. * 1. step:
  1581. * Iterate over all element IDs of the message which should have been signed and find the
  1582. * respective Reference element in the given message header
  1583. */
  1584. for (String id : verifyXMLSigRefElements.keySet()) {
  1585. getLogger().debug("Verifying digest for element '" + id + "'");
  1586. messageDigestsEqual = false;
  1587. calculatedReferenceDigest = verifyXMLSigRefElements.get(id);
  1588. for (ReferenceType reference : signature.getSignedInfo().getReference()) {
  1589. if (reference == null) {
  1590. getLogger().warn("Reference element to check is null");
  1591. continue;
  1592. }
  1593. // We need to check the URI attribute, not the Id attribute. But the Id must be set to sth. different than the IDs used in the body!
  1594. if (reference.getURI() == null) {
  1595. getLogger().warn("Reference ID element is null");
  1596. continue;
  1597. }
  1598. if (reference.getURI().equals('#' + id)) {
  1599. messageDigestsEqual = MessageDigest.isEqual(reference.getDigestValue(), calculatedReferenceDigest);
  1600. if (showSignatureVerificationLog) {
  1601. getLogger().debug("\n"
  1602. + "\tReceived digest of reference with ID '" + id + "': " + ByteUtils.toHexString(reference.getDigestValue()) + "\n"
  1603. + "\tCalculated digest of reference with ID '" + id + "': " + ByteUtils.toHexString(calculatedReferenceDigest) + "\n"
  1604. + "\t==> Match: " + messageDigestsEqual);
  1605. }
  1606. }
  1607. }
  1608. if (!messageDigestsEqual) {
  1609. getLogger().error("No matching signature found for ID '" + id + "' and digest value " +
  1610. ByteUtils.toHexString(calculatedReferenceDigest));
  1611. return false;
  1612. }
  1613. }
  1614. /*
  1615. * 2. step:
  1616. * Check the signature itself
  1617. */
  1618. ECPublicKey ecPublicKey = (ECPublicKey) verifyCert.getPublicKey();
  1619. Signature ecdsa;
  1620. boolean verified;
  1621. try {
  1622. getLogger().debug("Verifying signature of SignedInfo element ...");
  1623. // Check if signature verification logging is to be shown (for debug purposes)
  1624. if (showSignatureVerificationLog) showSignatureVerificationLog(verifyCert, signature, jaxbSignedInfo, ecPublicKey);
  1625. ecdsa = Signature.getInstance("SHA256withECDSA");
  1626. // The Signature object needs to be initialized by setting it into the VERIFY state with the public key
  1627. ecdsa.initVerify(ecPublicKey);
  1628. // The data to be signed needs to be supplied to the Signature object
  1629. byte[] exiEncodedSignedInfo = getExiCodec().getExiEncodedSignedInfo(jaxbSignedInfo);
  1630. ecdsa.update(exiEncodedSignedInfo);
  1631. // Java operates on DER encoded signature values, but the sent signature consists of the raw r and s value
  1632. byte[] signatureValue = signature.getSignatureValue().getValue();
  1633. byte[] derEncodedSignatureValue = getDEREncodedSignature(signatureValue);
  1634. // The verify() method will do both, the decryption and SHA256 validation. So don't hash separately before verifying
  1635. verified = ecdsa.verify(derEncodedSignatureValue);
  1636. return verified;
  1637. } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) {
  1638. getLogger().error(e.getClass().getSimpleName() + " occurred while trying to verify signature value", e);
  1639. return false;
  1640. }
  1641. }
  1642. /**
  1643. * Shows some extended logging while verifying a signature for debugging purposes.
  1644. * @param verifyCert The X509Certificate whose public key is used to verify the signature, used for printing the
  1645. * certificate's subject value
  1646. * @param signature The signature contained in the header of the V2GMessage
  1647. * @param ecPublicKey The public key used to verify the signature
  1648. */
  1649. private static void showSignatureVerificationLog(
  1650. X509Certificate verifyCert,
  1651. SignatureType signature,
  1652. JAXBElement<SignedInfoType> jaxbSignedInfo,
  1653. ECPublicKey ecPublicKey) {
  1654. byte[] computedSignedInfoDigest = generateDigest("", jaxbSignedInfo);
  1655. byte[] receivedSignatureValue = signature.getSignatureValue().getValue();
  1656. getLogger().debug("\n"
  1657. + "\tCertificate used to verify signature: " + verifyCert.getSubjectX500Principal().getName() + "\n"
  1658. + "\tPublic key used to verify signature: " + ByteUtils.toHexString(getUncompressedSubjectPublicKey(ecPublicKey)) + "\n"
  1659. + "\tReceived signature value: " + ByteUtils.toHexString(receivedSignatureValue) + " (Base64: " + Base64.getEncoder().encodeToString(receivedSignatureValue) + ")\n"
  1660. + "\tCalculated digest of SignedInfo element: " + ByteUtils.toHexString(computedSignedInfoDigest));
  1661. }
  1662. /**
  1663. * Java puts some encoding information into the ECPublicKey.getEncoded().
  1664. * This method returns the raw ECPoint (the x and y coordinate of the public key) in uncompressed form
  1665. * (with the 0x04 as first octet), aka the Subject Public Key according to RFC 5480
  1666. *
  1667. * @param ecPublicKey The ECPublicKey provided by Java
  1668. * @return The uncompressed Subject Public Key (with the first octet set to 0x04)
  1669. */
  1670. public static byte[] getUncompressedSubjectPublicKey(ECPublicKey ecPublicKey) {
  1671. byte[] uncompressedPubKey = new byte[65];
  1672. uncompressedPubKey[0] = 0x04;
  1673. byte[] affineX = ecPublicKey.getW().getAffineX().toByteArray();
  1674. byte[] affineY = ecPublicKey.getW().getAffineY().toByteArray();
  1675. // If the length is 33 bytes, then the first byte is a 0x00 which is to be omitted
  1676. if (affineX.length == 33)
  1677. System.arraycopy(affineX, 1, uncompressedPubKey, 1, 32);
  1678. else
  1679. System.arraycopy(affineX, 0, uncompressedPubKey, 1, 32);
  1680. if (affineY.length == 33)
  1681. System.arraycopy(affineY, 1, uncompressedPubKey, 33, 32);
  1682. else
  1683. System.arraycopy(affineY, 0, uncompressedPubKey, 33, 32);
  1684. return uncompressedPubKey;
  1685. }
  1686. /**
  1687. * An ECDSA signature consists of two positive integers r and s, each of the bit length equal to the curve size.
  1688. * When Java is creating an ECDSA signature, it is encoding it in the DER (Distinguished Encoding Rules) format.
  1689. * But in ISO 15118, we do not expect DER encoded signatures. Thus, this function takes the DER encoded signature
  1690. * as input and returns the raw r and s integer values of the signature.
  1691. * See further explanations in the @getDEREncodedSignature function for DER encoded ECDSA signatures.
  1692. *
  1693. * @param derEncodedSignature The DER encoded signature as a result from java.security.Signature.sign()
  1694. * @return A byte array containing only the r and s value of the signature
  1695. */
  1696. public static byte[] getRawSignatureFromDEREncoding(byte[] derEncodedSignature) {
  1697. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  1698. byte[] r = new byte[32];
  1699. byte[] s = new byte[32];
  1700. // Length of r is encoded in the fourth byte
  1701. int lengthOfR = derEncodedSignature[3];
  1702. // Length of r is encoded in the second byte AFTER r
  1703. int lengthOfS = derEncodedSignature[lengthOfR + 5];
  1704. // Length of r and s are either 33 bytes (including padding byte 0x00), 32 bytes (normal), or less (leftmost 0x00 bytes were removed)
  1705. try {
  1706. if (lengthOfR == 33) System.arraycopy(derEncodedSignature, 5, r, 0, lengthOfR - 1); // skip leftmost padding byte 0x00
  1707. else if (lengthOfR == 32) System.arraycopy(derEncodedSignature, 4, r, 0, lengthOfR);
  1708. else System.arraycopy(derEncodedSignature, 4, r, 32 - lengthOfR, lengthOfR); // destPos = number of leftmost 0x00 bytes
  1709. if (lengthOfS == 33) System.arraycopy(derEncodedSignature, lengthOfR + 7, s, 0, lengthOfS - 1); // skip leftmost padding byte 0x00
  1710. else if (lengthOfS == 32) System.arraycopy(derEncodedSignature, lengthOfR + 6, s, 0, lengthOfS);
  1711. else System.arraycopy(derEncodedSignature, lengthOfR + 6, s, 32 - lengthOfS, lengthOfS); // destPos = number of leftmost 0x00 bytes
  1712. } catch (ArrayIndexOutOfBoundsException e) {
  1713. getLogger().error("ArrayIndexOutOfBoundsException occurred while trying to get raw signature from DER encoded signature.", e);
  1714. }
  1715. try {
  1716. baos.write(r);
  1717. baos.write(s);
  1718. } catch (IOException e) {
  1719. getLogger().error("IOException occurred while trying to write r and s into DER-encoded signature", e);
  1720. }
  1721. byte[] rawRAndS = baos.toByteArray();
  1722. if (showSignatureVerificationLog) {
  1723. StringBuilder sb = new StringBuilder();
  1724. sb.append("Signature encoding DER -> raw:").append(System.lineSeparator());
  1725. sb.append("\tDER: ").append(ByteUtils.toHexString(derEncodedSignature)).append(System.lineSeparator());
  1726. sb.append("\tR: ").append(ByteUtils.toHexString(r)).append(System.lineSeparator());
  1727. sb.append("\tS: ").append(ByteUtils.toHexString(s)).append(System.lineSeparator());
  1728. sb.append("\tRaw: ").append(ByteUtils.toHexString(rawRAndS));
  1729. getLogger().debug(sb.toString());
  1730. }
  1731. return rawRAndS;
  1732. }
  1733. /**
  1734. * When encoded in DER, the signature - holding the
  1735. * x-coordinate of the elliptic curve point in the value "r"
  1736. * and the
  1737. * y-coordinate of the elliptic curve point in the value "s"
  1738. * - becomes the following sequence of bytes (in total somewhere between 68 and 72 bytes instead of 64 bytes):
  1739. *
  1740. * 0x30 len(z) 0x02 len(r) r 0x02 len(s) s
  1741. *
  1742. * where:
  1743. *
  1744. * - 0x30: is always the first byte of the DER encoded signature format (ASN.1 tag for sequence)
  1745. *
  1746. * - len(z): is a single byte value, encoding the length in bytes of the sequence z (remaining list of bytes)
  1747. * (from the first 0x02 to the end of the encoding); is a value between 0x43 and 0x46
  1748. *
  1749. * - 0x02: is a fixed value indicating that an integer value will follow (ASN.1 tag for int)
  1750. *
  1751. * - len(r): is a single byte value, encoding the length in bytes of r;
  1752. * Distinguished Encoding Rules (DER)-encoded integers are defined so that they can encode both positive and negative values
  1753. * (aka signed values). This means that the leftmost bit (aka most-significant bit in big-endian) indicates whether the value
  1754. * is positive (0) or negative (1).
  1755. * For ECDSA, however, the r and s values are positive integers. So the leftmost bit must be a 0. If it's not, a 0x00
  1756. * padding byte must be added.
  1757. *
  1758. * Furthermore, DER require that integer values are represented in the shortest byte representation possible. This
  1759. * effectively prohibits the use of leading zeroes (0x00) if the leftmost bit was not set to 1.
  1760. *
  1761. * So len(r) will either be 0x21 (33 bytes), 0x20 (32 bytes) or less (mostly not less than 0x1F (31 bytes)).
  1762. * Case 31 bytes or less: The leftmost bytes of the raw (non-DER-encoded) r are 0x00 and, according to DER, need to be
  1763. * removed so that r is DER-encoded in the shortest possible way. Also, the leftmost bit of the
  1764. * remaining byte array is 0 (-> a positive x-value).
  1765. * Case 32 bytes: What we would normally expect, as the x- and y-coordinates are positive values of 32 bytes length.
  1766. * The leftmost bit is set to 0 and the leftmost byte is not 0x00.
  1767. * Case 33 bytes: A padding 0x00 byte was added as the most significant (leftmost) byte because the raw (non-DER-encoded) r
  1768. * value had the leftmost bit set to 1, which would result in a negative value.
  1769. *
  1770. * - r: is the signed big-endian encoding of the value "r", of minimal length;
  1771. *
  1772. * - 0x02: is a fixed value indicating that an integer value will follow (ASN.1 tag for int)
  1773. *
  1774. * - len(s): is a single byte value, encoding the length in bytes of s;
  1775. * (See further explanation of len(r) that applies as well for len(s))
  1776. *
  1777. * - s: is the signed big-endian encoding of the value "s", of minimal length.
  1778. *
  1779. * @param rawSignatureValue The r and s values (each 32 bytes) of an ECDSA signature, given as a byte array of 64 bytes
  1780. * @return A byte array representing the DER-encoded version of the raw r and s values
  1781. */
  1782. private static byte[] getDEREncodedSignature (byte[] rawSignatureValue) {
  1783. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  1784. // First we separate x and y of coordinates into separate byte arrays r and s
  1785. byte[] r = new byte[32];
  1786. byte[] s = new byte[32];
  1787. try {
  1788. System.arraycopy(rawSignatureValue, 0, r, 0, 32);
  1789. System.arraycopy(rawSignatureValue, 32, s, 0, 32);
  1790. } catch (ArrayIndexOutOfBoundsException e) {
  1791. getLogger().error("ArrayIndexOutOfBoundsException occurred while trying to get DER encoded signature", e);
  1792. return new byte[0];
  1793. }
  1794. // Then encode both parts (r & s) individually
  1795. byte[] rDerEncoded = getDerEncodedSignatureValue(r);
  1796. byte[] sDerEncoded = getDerEncodedSignatureValue(s);
  1797. // And write everything with the proper header to the buffer
  1798. baos.write(0x30);
  1799. baos.write(rDerEncoded.length + sDerEncoded.length);
  1800. try {
  1801. baos.write(rDerEncoded);
  1802. baos.write(sDerEncoded);
  1803. } catch (IOException e) {
  1804. getLogger().error("IOException occurred while trying to write DER encoded signature r and s value", e);
  1805. }
  1806. byte[] derEncodedSignature = baos.toByteArray();
  1807. try {
  1808. baos.close();
  1809. } catch (IOException e) {
  1810. getLogger().error("IOException occurred while trying to close ByteArrayOutputStream", e);
  1811. }
  1812. if (showSignatureVerificationLog) {
  1813. StringBuilder sb = new StringBuilder();
  1814. sb.append("Signature encoding raw -> DER:").append(System.lineSeparator());
  1815. sb.append("\tRaw: ").append(ByteUtils.toHexString(rawSignatureValue)).append(System.lineSeparator());
  1816. sb.append("\tR: ").append(ByteUtils.toHexString(r)).append(System.lineSeparator());
  1817. sb.append("\tR (DER-encoded): ").append(ByteUtils.toHexString(rDerEncoded)).append(System.lineSeparator());
  1818. sb.append("\tS: ").append(ByteUtils.toHexString(s)).append(System.lineSeparator());
  1819. sb.append("\tS (DER-encoded): ").append(ByteUtils.toHexString(sDerEncoded)).append(System.lineSeparator());
  1820. sb.append("\tDER: ").append(ByteUtils.toHexString(derEncodedSignature));
  1821. getLogger().debug(sb.toString());
  1822. }
  1823. return derEncodedSignature;
  1824. }
  1825. /**
  1826. * Helper function which provides a partial DER encoding for positive integer values used for r and s
  1827. *
  1828. * @param value byte array containing a positive integer (non two's complement)
  1829. * @return DER-encoded value of r or s (depending on the @param), including int content type, length and, if needed, padding
  1830. */
  1831. private static byte[] getDerEncodedSignatureValue(byte[] value) {
  1832. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  1833. // Check if the value is negative which is equivalent to r[0] being bigger than 0x7f
  1834. boolean isFillByteNeeded = value[0] < 0;
  1835. int indexOfFirstNonNullValue = 0;
  1836. for (/* empty init statement */; indexOfFirstNonNullValue < value.length; indexOfFirstNonNullValue++) {
  1837. if (value[indexOfFirstNonNullValue] != 0) {
  1838. break;
  1839. }
  1840. }
  1841. byte derEncodedLength = (byte) (value.length - indexOfFirstNonNullValue);
  1842. baos.write(0x02);
  1843. if (isFillByteNeeded) {
  1844. baos.write(derEncodedLength + 1);
  1845. baos.write(0x00);
  1846. } else {
  1847. baos.write(derEncodedLength);
  1848. }
  1849. baos.write(value, indexOfFirstNonNullValue, value.length - indexOfFirstNonNullValue);
  1850. byte[] result = baos.toByteArray();
  1851. try {
  1852. baos.close();
  1853. } catch (IOException e) {
  1854. getLogger().error("IOException occurred while trying to close ByteArrayOutputStream", e);
  1855. }
  1856. return result;
  1857. }
  1858. /**
  1859. * Sets the SSLContext of the TLSServer and TLSClient with the given keystore and truststore locations as
  1860. * well as the password protecting the keystores/truststores.
  1861. *
  1862. * @param keyStorePath The relative path and filename for the keystore
  1863. * @param trustStorePath The relative path and filename for the truststore
  1864. * @param keyStorePassword The password protecting the keystore
  1865. */
  1866. public static void setSSLContext(
  1867. String keyStorePath,
  1868. String trustStorePath,
  1869. String keyStorePassword) {
  1870. KeyStore keyStore = SecurityUtils.getKeyStore(keyStorePath, keyStorePassword);
  1871. KeyStore trustStore = SecurityUtils.getKeyStore(trustStorePath, keyStorePassword);
  1872. try {
  1873. // Initialize a key manager factory with the keystore
  1874. KeyManagerFactory keyFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
  1875. keyFactory.init(keyStore, keyStorePassword.toCharArray());
  1876. KeyManager[] keyManagers = keyFactory.getKeyManagers();
  1877. // Initialize a trust manager factory with the truststore
  1878. TrustManagerFactory trustFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  1879. trustFactory.init(trustStore);
  1880. TrustManager[] trustManagers = trustFactory.getTrustManagers();
  1881. // Initialize an SSL context to use these managers and set as default
  1882. SSLContext sslContext = SSLContext.getInstance("TLS");
  1883. sslContext.init(keyManagers, trustManagers, null);
  1884. SSLContext.setDefault(sslContext);
  1885. } catch (NoSuchAlgorithmException | UnrecoverableKeyException | KeyStoreException |
  1886. KeyManagementException e) {
  1887. getLogger().error(e.getClass().getSimpleName() + " occurred while trying to initialize SSL context");
  1888. }
  1889. }
  1890. /**
  1891. * Checks the syntax of the EMAID according to Annex H.1 of ISO 15118-2
  1892. *
  1893. * @param certChain The contract certificate chain. The EMAID is read from the contract certificate's common name
  1894. * @return True, if the syntax is valid, false otherwise
  1895. */
  1896. public static boolean isEMAIDSyntaxValid(X509Certificate contractCertificate) {
  1897. String emaid = getEMAID(contractCertificate).getValue().toUpperCase();
  1898. if (emaid.length() < 14 || emaid.length() > 18) {
  1899. getLogger().error("EMAID is invalid. Its length (" + emaid.length() + ") mus be between "
  1900. + "14 (min, excluding separators) and 18 (max, including separators)");
  1901. return false;
  1902. }
  1903. String emaidWithoutSeparator = emaid.replace("-", "");
  1904. // Check country code
  1905. if (Character.isDigit(emaidWithoutSeparator.charAt(0)) || Character.isDigit(emaidWithoutSeparator.charAt(1))) {
  1906. getLogger().error("EMAID (" + emaid + ") is invalid, the first two characters must not be a digit");
  1907. return false;
  1908. }
  1909. // Check provider ID
  1910. if (! (Character.isLetterOrDigit(emaidWithoutSeparator.charAt(2)) &&
  1911. Character.isLetterOrDigit(emaidWithoutSeparator.charAt(3)) &&
  1912. Character.isLetterOrDigit(emaidWithoutSeparator.charAt(4))) ) {
  1913. getLogger().error("EMAID (" + emaid + ") is invalid, the provider ID must be alpha-numerical");
  1914. return false;
  1915. }
  1916. // Check emaInstance
  1917. if (! (Character.isLetterOrDigit(emaidWithoutSeparator.charAt(5)) &&
  1918. Character.isLetterOrDigit(emaidWithoutSeparator.charAt(6)) &&
  1919. Character.isLetterOrDigit(emaidWithoutSeparator.charAt(7)) &&
  1920. Character.isLetterOrDigit(emaidWithoutSeparator.charAt(8)) &&
  1921. Character.isLetterOrDigit(emaidWithoutSeparator.charAt(9)) &&
  1922. Character.isLetterOrDigit(emaidWithoutSeparator.charAt(10)) &&
  1923. Character.isLetterOrDigit(emaidWithoutSeparator.charAt(11)) &&
  1924. Character.isLetterOrDigit(emaidWithoutSeparator.charAt(12)) &&
  1925. Character.isLetterOrDigit(emaidWithoutSeparator.charAt(13))) ) {
  1926. getLogger().error("EMAID (" + emaid + ") is invalid, the eMA instance must be alpha-numerical");
  1927. return false;
  1928. }
  1929. return true;
  1930. }
  1931. public static void setExiCodec(ExiCodec exiCodecChoice) {
  1932. exiCodec = exiCodecChoice;
  1933. }
  1934. private static ExiCodec getExiCodec() {
  1935. return exiCodec;
  1936. }
  1937. }