Signature hash does not match как решить
Перейти к содержимому

Signature hash does not match как решить

  • автор:

Signature hash does not match как исправить или как подключить opencart к marketplace ( маркетплейс )?

Как подключить opencart 3 к marketplace ( маркетплейс )

Opencart начиная с версии 3 предоставил возможность прямого подключения к собственному маркетплейс (marketplace) через админ панель. Эта функция сильно упростила установку различных модулей как бесплатных так и платных тем самым давая возможность с помощью одного клика установить дополнительные расширения для вашего магазина.

В первый раз попытка соединить мой магазин на opencart с marketplace закончилась ошибкой: Signature hash does not match. Мне пришлось серьезно поискать решения данного вопроса в интернете, но результат был тем же. В последствии я нашел решение самостоятельно и оно оказалось очень простым.

Если вы уже прошли все этапы подключения в маркетпласе и у вас выдается ошибка Signature hash does not match тогда перейдите к разделу ( Signature hash does not match как исправить ? ).

Полный список этапов подключения opencart к маркетпласе

1 Прейдите в админ меню маркетплейсе:

Как подключить opencart 3 к marketplace ( маркетплейс ) 1

2 В открывшейся странице слева вверху нажмите:

Как подключить opencart 3 к marketplace ( маркетплейс ) 2

3 Перейдите в указанный пункт ниже

Как подключить opencart 3 к marketplace ( маркетплейс ) 3

4 В личном кабинете найдите раздел «your stores» и перейдите в него:

Как подключить opencart 3 к marketplace ( маркетплейс ) 4

5 Добавьте свой магазин нажав на этот пункт меню:

Как подключить opencart 3 к marketplace ( маркетплейс ) 5

6 В открывшемся поле введите адрес своего магазина ( только адрес без https:// без www. Как в примере на картинке ):

Как подключить opencart 3 к marketplace ( маркетплейс ) 6

7 Это самый важный пункт в открывшейся странице с username и API Secret скопируйте username, и обязательно скопируйте API Secret через кнопку:

Как подключить opencart 3 к marketplace ( маркетплейс ) 7

8 Как вы уже догадались эту информацию нужно добавить в админ панели в раздел маркетпласе.

Как подключить opencart 3 к marketplace ( маркетплейс ) 8

Signature hash does not match как исправить ?

Как подключить opencart 3 к marketplace ( маркетплейс ) 9

Данная ошибка появляется когда в поле добавления адреса магазина присутствуют лишние символы должен быть только адрес вот так: test.com (без http:// https: www) это важный момент. Так же может появляться из за не корректно скопированного API Secret ( Ключа ), по этому рекомендуется копировать с помощью специальной кнопки:

Как подключить opencart 3 к marketplace ( маркетплейс ) 10

Маркетпласе ( marketplace ) opencart и localhost

Итак ответ на многочисленные вопросы. Работает ли opencart маркетпласе на localhost например для разработки магазина? Да.

Необходимо добавить имя вашего локального хостинга для получения ключа.

Рекомендуем сделать резервную копию магазина перед установками расширений.

Если у вас возникли сложности или вопросы обращайтесь к нам через страницу контактов мы с радостью вам поможем.

[SOLVED] Signature hash does not match

Hi All
Installed opencart Version 3.0.3.2 and added a theme.
Everything seemed on first glance to work ok. Done lots of modifications to the site and now realised that the market place API doen’t work.
Added a store to my opencart account and added API secret key and username and it says accepted. But still have the red triangle in the top right corner. Can’t install any new mods to the site.
Scrolled through the web and can’t find a recent post on how to fix.
So appologies if this has been answered before.
Thanks in advance
Mark

java signature «hash values do not match»

I am trying to send an xml document to a remote server. I sign the document using a keystore that contains a private key and certificate. But when the remote server gets the xml, it responds with «hash values do not match». Research on this error says that the xml document is being changed after it is signed. My java code does not make any such changes after the signing, as far as I can tell. I have also tried removing all the whitespace from the xml, just before signing, but that had no effect. Here is part of the signature xml that is being generated:

          yFfex/IpBJ4zrAFxJ5kkTKBrIR8=   F9dnhEW/RN4IphLUfSu0kCJ/+0L6KtzJlxuptzWYL52su1/mfpnaQaqdHW/iJeLUL4PJZ47hxXwwMZj5y9GJMxnedz+XSu+4GJ5dwEY… aqQTJg==   CN=RapidSSL RSA CA 2018,OU=www.digicert.com,O=DigiCert Inc,C=US 8986524346372316412121820876514917638  MIIFtTCCBJ2gAwIBAgIQBsK927DS8wePBQjvzVX9BjANBgkqhkiG9w0BAQsFADBeMQswCQYDVQQGEwJVUzEVMBMGA1UEChM… YRtXpTI5y30r02yhghe//nMCL3MthO/gjEqGiLb1CxOncQ+j4A8+cfN+RR2fgA==     

When the remote server tries to decode this value, it is apparently not coming up with the original signed version. Note that Reference URI=”Body” means that only the section of xml that contains the is being used to generate the DigestValue. Here is the section of xml that contains “Id=Body”:

    2019-12-09T18:26Z RO      
2019-12-09T18:26Z
GRAND CHEROKEE 2015

Here is the java code to sign the xml. It generates and then inserts the Signature block into the SOAP-SEC:Signature element shown in the example above:

 private void buildSignatureBlock5(String privateKeyPath, String publicKeyPath) < // Create a DOM XMLSignatureFactory that will be used to generate the signature. XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); // Create a Reference to the enveloped document (in this case, // you are signing just the element with , so a URI of "#Body" signifies // that), and also specify the SHA1 digest algorithm and the xml-exc-c14n# Transform. Reference ref = null; try < ref = fac.newReference ("#Body", fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList (fac.newTransform ("http://www.w3.org/2001/10/xml-exc-c14n#", (TransformParameterSpec) null)), null, null); >catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException e) < // TODO Auto-generated catch block e.printStackTrace(); >// Create the SignedInfo. SignedInfo si = null; try < si = fac.newSignedInfo (fac.newCanonicalizationMethod (CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null), fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(ref)); >catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException e) < // TODO Auto-generated catch block e.printStackTrace(); >// Load the KeyStore and get the signing key and certificate. KeyStore ks = null; try < ks = KeyStore.getInstance("JKS"); >catch (KeyStoreException e) < // TODO Auto-generated catch block e.printStackTrace(); >try < ks.load(new FileInputStream(storage_path +"/keys/company.jks"), "changeit".toCharArray()); >catch (NoSuchAlgorithmException | CertificateException | IOException e) < // TODO Auto-generated catch block e.printStackTrace(); >KeyStore.PrivateKeyEntry keyEntry = null; try < keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry ("1", new KeyStore.PasswordProtection("changeit".toCharArray())); >catch (NoSuchAlgorithmException | UnrecoverableEntryException | KeyStoreException e) < // TODO Auto-generated catch block e.printStackTrace(); >X509Certificate cert = (X509Certificate) keyEntry.getCertificate(); // Create the KeyInfo containing the X509Data. KeyInfoFactory kif = fac.getKeyInfoFactory(); List x509Content = new ArrayList(); String issuerName = cert.getIssuerX500Principal().getName(); BigInteger serialNumber = cert.getSerialNumber(); X509IssuerSerial issuer = kif.newX509IssuerSerial(issuerName, serialNumber); x509Content.add(issuer); x509Content.add(cert); X509Data xd = kif.newX509Data(x509Content); KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd)); // Create a DOMSignContext and specify the RSA PrivateKey and location of the resulting XMLSignature's parent element. Element envHeaderSig = (Element) document.getElementsByTagName("SOAP-SEC:Signature").item(0); DOMSignContext dsc = new DOMSignContext(keyEntry.getPrivateKey(), envHeaderSig); // Create the XMLSignature, but don't sign it yet. XMLSignature signature = fac.newXMLSignature(si, ki); try < signature.sign(dsc); //ResourceResolverException: Cannot resolve element with ID Body >catch (MarshalException | XMLSignatureException e) < // TODO Auto-generated catch block e.printStackTrace(); >removeWhitespaceFromSignature(); > //hack to remove unwanted CR at the end of each line in SignatureValue and X509Certificate private void removeWhitespaceFromSignature()

I’m providing the XML to sign in the following line:

Element envHeaderSig = (Element) document.getElementsByTagName("SOAP-SEC:Signature").item(0); 

But I don’t know how the subsequent “signature.sign” processes that data. Does it remove whitespace? Apparently, whatever it does results in the decoding algorithm on the remote server side producing different XML, creating a mismatch in the DigestValue (hash) it calculates. Here is the java code used to send the soap request:

send(String xmlSoapString) throws IOException < HttpURLConnection connection = null; OutputStreamWriter wr = null; BufferedReader in = null; String result = ""; try < URL connectionUrl = new URL(url); connection = (HttpURLConnection) connectionUrl.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); //set connection properties - guessing at equivalents from PHP headers connection.setRequestProperty("accept","image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*"); connection.setDefaultUseCaches(false); // "cache-control: no-cache" connection.setRequestProperty("content-type","text/html"); connection.setRequestProperty("pragma","no-cache"); connection.setRequestProperty("time_stamp",timestamp_unix); connection.setRequestProperty("timestamp",timestamp); connection.setRequestProperty("SentTimeStamp",timestamp); connection.setRequestProperty("version","2.0"); connection.setRequestProperty("Content-length",String.valueOf(documentToString(xml).length())); Map> requestProperties = connection.getRequestProperties(); String userCredentials = userId + ":" + dmsId; String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userCredentials.getBytes())); connection.setRequestProperty("Authorization", basicAuth); setSoapHeader(connection); wr = new OutputStreamWriter(connection.getOutputStream()); wr.write(xmlSoapString); //send soap request to remote server wr.flush(); try < in = new BufferedReader(new InputStreamReader(connection.getInputStream())); >catch (Exception e) < in = new BufferedReader(new InputStreamReader(connection.getErrorStream())); >StringBuilder bodyBuilder = new StringBuilder(); String inputLine; while ((inputLine = in.readLine()) != null) < bodyBuilder.append(inputLine); >in.close(); result = String.valueOf( bodyBuilder.toString()); System.out.println("Response mt24 mb12">
    javasslsoapdigital-signaturex509certificate
)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this question" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="question" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="1" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f4.0%2f" data-se-share-sheet-license-name="CC BY-SA 4.0" data-s-popover-placement="bottom-start">Share
asked Dec 10, 2019 at 18:30
1
    I tried the Validate.java example given in the official documentation here: docs.oracle.com/javase/9/security/…. I ran "java Validate signature.xml" and it failed with "Signature failed core validation signature validation status: false ref[0] validity status: false". How are we supposed to get our stuff to work when we can't even get the simple official example to work.
    – user3217883
    Dec 10, 2019 at 21:54
Add a comment|

2 Answers 2

Reset to default
0

Could be due to the remote server not using the same xml canonicalization approach(exclusive) that you are using. This can cause the hash to be computed on an xml that is syntactically different.

)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this answer" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="answer" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="2" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f4.0%2f" data-se-share-sheet-license-name="CC BY-SA 4.0" data-s-popover-placement="bottom-start">Share
answered Dec 11, 2019 at 23:11
Add a comment|
0

I eventually got this to work. It was very complicated. Apparently the #body section was not being selected correctly. Here is the code that got it right.

private void buildSignatureBlock() < // Create a DOM XMLSignatureFactory that will be used to generate the signature. XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); // Create a Reference to the document (in this case, you are signing just the element with // , so a URI of "#Body" signifies that), and also specify the SHA1 digest algorithm // and the xml-exc-c14n# Transform. Reference ref = null; try < ref = fac.newReference ("#Body", fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList (fac.newTransform ("http://www.w3.org/2001/10/xml-exc-c14n#", (TransformParameterSpec) null)), null, null); >catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException e) < // TODO Auto-generated catch block e.printStackTrace(); >// Create the SignedInfo. SignedInfo si = null; try < si = fac.newSignedInfo (fac.newCanonicalizationMethod (CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null), fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(ref)); >catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException e) < // TODO Auto-generated catch block e.printStackTrace(); >// Load the KeyStore and get the signing key and certificate. KeyStore ks = null; try < ks = KeyStore.getInstance("JKS"); >catch (KeyStoreException e) < // TODO Auto-generated catch block e.printStackTrace(); >try < ks.load(new FileInputStream("src/main/resources/xml/project/keys/project.jks"), "password".toCharArray()); >catch (NoSuchAlgorithmException | CertificateException | IOException e) < // TODO Auto-generated catch block e.printStackTrace(); >KeyStore.PrivateKeyEntry keyEntry = null; try < keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry ("1", new KeyStore.PasswordProtection("password".toCharArray())); >catch (NoSuchAlgorithmException | UnrecoverableEntryException | KeyStoreException e) < // TODO Auto-generated catch block e.printStackTrace(); >X509Certificate cert = (X509Certificate) keyEntry.getCertificate(); // Create the KeyInfo containing the X509Data. KeyInfoFactory kif = fac.getKeyInfoFactory(); List x509Content = new ArrayList(); String issuerName = cert.getIssuerX500Principal().getName(); BigInteger serialNumber = cert.getSerialNumber(); X509IssuerSerial issuer = kif.newX509IssuerSerial(issuerName, serialNumber); x509Content.add(issuer); x509Content.add(cert); X509Data xd = kif.newX509Data(x509Content); KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd)); // Create a DOMSignContext and specify the RSA PrivateKey and location of the resulting XMLSignature's parent element. Element envHeaderSig = (Element) document.getElementsByTagName("SOAP-SEC:Signature").item(0); // Create the XMLSignature, but don't sign it yet. XMLSignature signature = fac.newXMLSignature(si, ki); try < Node envelope = document.getFirstChild(); Node header = envelope.getFirstChild(); DOMSignContext sigContext = new DOMSignContext(keyEntry.getPrivateKey(), header); // Need to distinguish the Signature element in DSIG (from that in SOAP) sigContext.putNamespacePrefix(XMLSignature.XMLNS, "ds"); // register Body ID attribute sigContext.setIdAttributeNS(getNextSiblingElement(header),"http://schemas.xmlsoap.org/soap/security/2000-12","id"); signature.sign(sigContext); >catch (MarshalException | XMLSignatureException e) < // TODO Auto-generated catch block e.printStackTrace(); >///VALIDATE the signature Element sigElement = envHeaderSig; DOMValidateContext valContext = new DOMValidateContext(cert.getPublicKey(), sigElement); Element envelope = getFirstChildElement(document); Element header = getFirstChildElement(envelope); valContext.setIdAttributeNS (getNextSiblingElement(header), "http://schemas.xmlsoap.org/soap/security/2000-12","id"); boolean isValid = false; try < isValid = signature.validate(valContext); >catch (XMLSignatureException e) < e.printStackTrace(); >System.out.println("Validating the signature. " + (isValid ? "valid" : "invalid")); >

Here's a couple functions that pull the needed elements from the document for signature validation:

private static Element getFirstChildElement(org.w3c.dom.Node node) < org.w3c.dom.Node child = node.getFirstChild(); while (child != null && child.getNodeType() != org.w3c.dom.Node.ELEMENT_NODE) < child = child.getNextSibling(); >return (Element) child; > public static Element getNextSiblingElement(org.w3c.dom.Node node) < org.w3c.dom.Node sibling = node.getNextSibling(); while (sibling != null && sibling.getNodeType() != org.w3c.dom.Node.ELEMENT_NODE) < sibling = sibling.getNextSibling(); >return (Element) sibling; > 

Signature hash does not match! OpenCart Solution

While installing modules from the marketplace directly from the website you may encounter an error message like “Signature hash does not match!”, solution for this is following for OpenCart version 3.0.2.0:

  • Log in to your OpenCart account https://www.opencart.com/index.php?route=account/login
  • In the Dashboard you will see “Your Stores”, click it then click the “Add Store” button.

Add signature hash for your store in Opencart

  • Then Add your store information which is the domain name

Add domain name for signature hash

  • Then click submit, you will get details of your username and secret key

Opencart Marketplace API

  • Go to your website and log in to the admin section.
  • Go to Extensions >> Marketplace and click the setting button

Install extension form Marketplace Opencart

  • It will show the popup where you enter the username and the secret key, enter them that you get above at opencart.com account dashboard

Opencart Marketplace API add

  • Then you are set to install directly from OpenCart Marketplace from the dashboard.

For installation of OpenCart extensions, please watch the following video:

Uploading, installing, configuring, uninstalling OpenCart 3 module/extension

Please let us know if you have any questions or suggestions, please subscribe to our YouTube Channel for Opencart video tutorials. You can also find us on Twitter and Facebook. Enjoy!

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *