PHP7: Unknown hashing algorithm: sha256 - php-7

In PHP7, when I hash a string like this:
$hash = hash("sha256", "password");
I have this warning:
Unknown hashing algorithm: sha256
In PHP 5.2.9, it was working. Is the sha256 deprecated in php7? Other idea?
Notes
the extension "php_openssl.dll" is enabled.
hash("sha512", "password"); // WORKS !
print_r( hash_algos() );
[0] => md2 [1] => md4 [2] => md5 [3] => sha1 [4] => sha224 [5] => sha256
[6] => sha384 [7] => sha512 ...

I know that you got it to work, but I wanted to add that I've looked through the PHP7 source code and there's simply no reason why it shouldn't work every time.
In ./ext/hash/hash.c, we define our table of available hashes:
PHP_MINIT_FUNCTION(hash)
{
// ...
zend_hash_init(&php_hash_hashtable, 35, NULL, NULL, 1);
// ...
php_hash_register_algo("sha224", &php_hash_sha224_ops);
php_hash_register_algo("sha256", &php_hash_sha256_ops);
php_hash_register_algo("sha384", &php_hash_sha384_ops);
php_hash_register_algo("sha512", &php_hash_sha512_ops);
// ...
}
php_hash_register_algo() is also very simple:
PHP_HASH_API void php_hash_register_algo(const char *algo, const php_hash_ops *ops) /* {{{ */
{
size_t algo_len = strlen(algo);
char *lower = zend_str_tolower_dup(algo, algo_len);
zend_hash_str_add_ptr(&php_hash_hashtable, lower, algo_len, (void *) ops);
efree(lower);
}
So what of php_hash_sha256_ops? That's defined in ./ext/hash/hash_sha.c:
const php_hash_ops php_hash_sha256_ops = {
(php_hash_init_func_t) PHP_SHA256Init,
(php_hash_update_func_t) PHP_SHA256Update,
(php_hash_final_func_t) PHP_SHA256Final,
(php_hash_copy_func_t) php_hash_copy,
32,
64,
sizeof(PHP_SHA256_CTX)
};
By looking at the code in this file, you can also see that there are no preventative conditions in PHP_SHA256Init(), PHP_SHA256Update(), or PHP_SHA256Final(). I can't find a single possible way that sha256 could be disabled.

What it boiled down to for me was that due to a forgotten comment in configs I was using mod_php with mpm_event apache. So non-thread-safe php7 in a threaded environment, hence shared memory corruption and a number of problems, one of them being sha1 was unavailable after some random uptime.

1)Open localhost/phpmyadmin or 127.0.0.1/phpmyadmin which certainly gives you an error.
2).To fix this, restart the server to start the service of PHPMYADMIN.
3).if you are on local server, open your xampp or wampp, stop all services then start it.
4).This will fix your all issues for sure

I had the same issue today. It resolved itself after a reboot

just needed to Restart xampp or MAMP to fix the issue.

Related

Cannot import module from Cypress spec file

I am trying to use the #peculiar/x509 library to decode a CSR to use some of the information in my tests. The tests are using Cypress.
Here is an extract of my code:
import * as x509 from '#peculiar/x509';
const request = {
certificateSigningRequest: `-----BEGIN CERTIFICATE REQUEST-----
...
-----END CERTIFICATE REQUEST-----`,
};
describe('PKI', () => {
it('works', () => {
console.log(x509);
const stringPEM = request.certificateSigningRequest
.replace(/(-----(BEGIN|END) CERTIFICATE REQUEST-----|\n)/g, "");
const cert = new x509.X509Certificate(stringPEM);
console.log(cert.subject);
return;
// Stuff I want to test
});
});
When I try to log the x509 variable it returns an empty object.
And on the const cert = new x509.X509Certificate(stringPEM); line, I get an error:
x509.X509Certificate is not a constructor.
If I try to set up a simple project with a Typescript file to import the library and just log the x509 variable, it displays all the exports correctly.
I can't figure why it behaves like that with Cypress, so any help is appreciated.
EDIT: Diving a bit more into how Cypress works, I now understand that my assumption about the spec files running/controlled in a Node process was wrong. Spec files are running in the browser. So I would need to inject the browser version of the library in the spec file.
This can be done via the plugin API of Cypress, because it runs in the Cypress node process.
You can import a specific build, either x509.es.js or x509.cjs.js and your code works. The base #peculiar/x509 is for <script> inclusion.
One thing, the BEGIN and END tokens need to remain in the request for it to be recognized.
import * as x509 from '#peculiar/x509/build/x509.es.js'
// const x509 = require('#peculiar/x509/build/x509.cjs.js') // alternative
// hard left for multiline strings, otherwise request is not correctly formatted
const request = {
certificateSigningRequest: `-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----`,
};
// copied from #peculiar/x509 to verify format - not necessary for test
const isPem = (data) => {
return typeof data === "string"
&& /-{5}BEGIN [A-Z0-9 ]+-{5}([a-zA-Z0-9=+/\n\r]+)-{5}END [A-Z0-9 ]+-{5}/g.test(data);
}
console.log(isPem(request.certificateSigningRequest))
describe('PKI', () => {
it('works', () => {
console.log(x509);
const stringPEM = request.certificateSigningRequest // leave in BEGIN and END
const cert = new x509.X509Certificate(stringPEM);
console.log(cert.subject); // prints e.g. "CN=Test certificate, E=some#email.net"
return;
// Stuff I want to test
});
});
Possibly due to NodeJS version issue.
The X509Certificate was added recently in NodeJS version 15.6.0. Changelog here. So it requires that version. It might have worked on your simple project because of a newer NodeJS version.
And by default, Cypress is using its bundled NodeJS version, which since Cypress version 7.0.0 to 8.2.0, it's using bundled NodeJS version 14.16.0, as per the changelog here:
The bundled Node.js version was upgraded from 12.18.3 to 14.16.0.
So you can try changing/overriding the bundled NodeJS version in Cypress configuration to version 15.6.0, as per this configuration:
nodeVersion

LWP with SSL and client certificates

Debian 10. I try to connect to a remote server with certificate. However connection fails with 500 error. DEBUG: .../IO/Socket/SSL.pm:2593: global error: Failed to load certificate from file (no PEM, DER or PKCS12) error:0D0680A8:asn1 encoding routines:asn1_check_tlen:wrong tag.
Same code with same certificate works fine with several Debian 9. I have tried different versions with Debian 10 - of IO-Socket_SSL (ex. 2.044 - 2.060), LWP-Protocol-https (ex. 6.05 - 6.07) with no luck.
For clear experiment I took fresh from provider debian images with 9 & 10. It works with basic perl modules with ver 9 and fails with ver 10.
I need a piece of help & advise , cause I'm loosing hope :(
use LWP;
use LWP::UserAgent;
use LWP::Protocol::https;
use LWP::Debug qw(+);
use Net::SSL;
use IO::Socket::SSL qw(debug4);
$ENV{HTTPS_CERT_FILE} = "cert.crt";
$ENV{HTTPS_KEY_FILE} = "private.key";
$ENV{PERL_LWP_SSL_VERIFY_HOSTNAME} = 0;
$ENV{HTTPS_DEBUG} = 1;
my $ua = LWP::UserAgent->new;
$ua->ssl_opts(
SSL_verify_mode => 0,
verify_hostname => 0,
SSL_cert_file => "cert.crt",
SSL_key_file => "private.key"
);
my $req = HTTP::Request->new(POST => "https://server:775/api");
$req->header('content-type' => 'application/soap+xml; charset=utf-8; action="http://tempuri.org/ICodeRequestOnline/GetProtocolVersion"');
my $txt= qq{<?xml version="1.0" encoding="UTF-8"?><soap:Envelope>...</soap:Envelope>};
$req->content($txt);
my $resp = $ua->request($req);
print $resp->as_string;

Soap client with Node and strong-soap returning error with cerficate

I am using strong-soap (but with node-soap is the same result) node module to connect with soap services.
In the first step I am creating the client and trying to connect one method in this case "doLogin" method.
My code is:
soap.createClient(url, clientOptions, (err, client) => {
var loginApi = { UserName: "xxxx", Password: "xxxxxx" };
var loginUser = {
userName: "comercial#xxxxx.com"
};
client.addSoapHeader(header);
//client.setSecurity(new soap.BasicAuthSecurity(loginApi));
// we now have a soapClient - we also need to make sure there's no `err` here.
client.doLogin(loginUser, (err, result) => {
//'result' is the response body
console.error(err);
console.log("Result: \n" + JSON.stringify(result));
});
But the variable err is returning this error in the console:
{ Error: unable to verify the first certificate
at TLSSocket.<anonymous> (_tls_wrap.js:1105:38)
at emitNone (events.js:106:13)
at TLSSocket.emit (events.js:208:7)
at TLSSocket._finishInit (_tls_wrap.js:639:8)
at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:469:38) code:
'UNABLE_TO_VERIFY_LEAF_SIGNATURE' }
and result is undefined.
why is happening this error?
result is undefined by the error?
I have faced same error, unable to verify the first certificate.
This is because of SSL cerficate isnt verified.
Your nodejs script calls your server, it is going to carry out the full TLS check process (as you would hope). This will check the certificates for validity etc.
To work around this issue, you can run the following Steps:
npm config set strict-ssl false
As a best practice, it is wise to set it back to true afterwords so you do not accidentally install an untrusted module that you actually do not trust.
After this,
npm cache clean --force
Add the following environment variable:
NODE_TLS_REJECT_UNAUTHORIZED=0
For Linux:
export NODE_TLS_REJECT_UNAUTHORIZED=0
For Nginx
NODE_TLS_REJECT_UNAUTHORIZED=0
For Window:
this will set for only current command prompt screen,
set NODE_TLS_REJECT_UNAUTHORIZED=0
This has solved issue for me. Please try
Note: Make sure you do not leave this option on in production. Please don't disable TLS checks at all.
FIXED:
I have added correct certificates and rejectUnauthorized: false to create client and added "envelope" directive to the headers and now it is working.
I donĀ“t like the instruction rejectUnauthorized: false by security topics and I would like to know how to remove this in production environment.
Thank you!!

BigCommerce PHP API Ciper Error

I am using the BigCommerce PHP API and am receiving this error when it attempts to connect to either my store or the webdav store:
failed setting cipher list
From the same server I have connected to both sites using cURL via the command line. I have the cURL php module installed with SSL enabled. Any thoughts would be appreciated.
I think you have to enable the 'rsa_rc4_128_sha' cipher. It might not be enabled by default. Can you try
Connection::setCipher()
before making a request? By default this sets the cipher to the above cipher as default.
There is some history on this in the BC github repos -
https://github.com/bigcommerce/bigcommerce-api-php/pull/10
https://github.com/bigcommerce/bigcommerce-api-php/pull/11
Hope this helps.
I was using wamp and tested this just now.
To fix this I updated the connection api file with
curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($this->curl, CURLOPT_CAINFO, 'C:\xampp\htdocs\big\Bigcommerce\Certs\cacert.pem');
and the file from
http://curl.haxx.se/docs/caextract.html
We use an object based upon the following
<?php
// provision for laziness
if(
(array_key_exists('store_url', (array)$settings)) &&
(array_key_exists('username', $settings)) &&
(array_key_exists('api_key', $settings))
) {
// Config Basic
BC::configure(
array(
'store_url' => $settings['store_url'],
'username' => $settings['username'],
'api_key' => $settings['api_key']
)
);
// Set Cipher if needed
if(array_key_exists('cipher',$settings)) {
BC::setCipher('RC4-SHA');
} else {
BC::verifyPeer(false);
}
// Set Proxy if needed
if(array_key_exists('proxy',$settings)) {
BC::useProxy($settings['proxy']['url'], $settings['proxy']['port']);
}
}
// Run your code here...

Socket Hang Up when using https.request in node.js

When using https.request with node.js v04.7, I get the following error:
Error: socket hang up
at CleartextStream.<anonymous> (http.js:1272:45)
at CleartextStream.emit (events.js:61:17)
at Array.<anonymous> (tls.js:617:22)
at EventEmitter._tickCallback (node.js:126:26)
Simplified code that will generate the error:
var https = require('https')
, fs = require('fs')
var options = {
host: 'localhost'
, port: 8000
, key: fs.readFileSync('../../test-key.pem')
, cert: fs.readFileSync('../../test-cert.pem')
}
// Set up server and start listening
https.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'})
res.end('success')
}).listen(options.port, options.host)
// Wait a second to let the server start up
setTimeout(function() {
var clientRequest = https.request(options, function(res) {
res.on('data', function (chunk) {
console.log('Called')
})
})
clientRequest.write('')
clientRequest.end()
}, 1000)
I get the error even with the server and client running on different node instances and have tested with port 8000, 3000, and 443 and with and without the SSL certificates. I do have libssl and libssl-dev on my Ubuntu machine.
Any ideas on what could be the cause?
In
https.createServer(function (req, res) {
you are missing options when you create the server, should be:
https.createServer(options, function (req, res) {
with your key and cert inside
I had a very similar problem where the response's end event never fired.
Adding this line fixed the problem:
// Hack to emit end on close because of a core bug that never fires end
response.on('close', function () {response.emit('end')});
I found an example of this in the request library mentioned in the previous answer.
Short answer: Use the the latest source code instead of the one you have. Store it where you will and then require it, you are good to go.
In the request 1.2.0 source code, main.js line 76, I see
http.createClient(options.uri.port, options.uri.hostname, options.uri.protocol === 'https:');
Looking at the http.js source code, I see
exports.createClient = function(port, host) {
var c = new Client();
c.port = port;
c.host = host;
return c;
};
It is requesting with 3 params but the actual function only has 2. The functionality is replaced with a separate module for https.
Looking at the latest main.js source code, I see dramatic changes. The most important is the addition of require('https').
It appears that request has been fixed but never re-released. Fortunately, the fix seems to work if you just copy manually from the raw view of the latest main.js source code and use it instead.
I had a similar problem and i think i got a fix. but then I have another socket problem.
See my solution here: http://groups.google.com/group/nodejs/browse_thread/thread/9189df2597aa199e/b83b16c08a051706?lnk=gst&q=hang+up#b83b16c08a051706
key point: use 0.4.8, http.request instead of http.createClient.
However, the new problem is, if I let the program running for long time, (I actually left the program running but no activity during weekend), then I will get socket hang up error when I send a request to http Server. (not even reach the http.request). I don't know if it is because of my code, or it is different problem with http Server