I am creating a JWT Token using a private key in PHP. For this I am using the OpenSSL library.Before anything I will share my code :
PHP
$header = [ self::ALG => self::RS256, self::TYP => self::JWT ]; $payload = [ "iss" => $this->getClientID(), "iat" => time(), "exp" => time()+999 ]; $header = base64_encode(json_encode($header)); $payload = base64_encode(json_encode($payload)); $token = $header.".".$payload; $pkey = openssl_pkey_get_private($this->getPrivateKey(), $this->getPassPhrase()); openssl_sign($token, $signature, $pkey, 'sha256'); //no algorithm specifically for rs256 $sign = base64_encode($signature); return $token.".".$sign;
So, this JWT Token will be used for authentication in a server which I am trying to hit. But I get the response from the external server as a Bad Request
, problem happening in my JWT token creation.
With same credentials, I tried in javascript using the library jsrsasign
and it then gives me the correct response.
JAVASCRIPT
// Headervar oHeader = { alg: 'RS256', typ: 'JWT' };// Payloadvar oPayload = {};var tNow = rs.KJUR.jws.IntDate.get('now');var tEnd = tNow + 1000;oPayload.iss = "playground.pizza";oPayload.iat = tNow;oPayload.exp = tEnd;var sHeader = JSON.stringify(oHeader);var sPayload = JSON.stringify(oPayload);var pkey = "my private key" //I replaced all the new line with \n here and had in one linevar prvKey = rs.KEYUTIL.getKey(pkey, "my_pass_phrase");var sJWT = rs.KJUR.jws.JWS.sign("RS256", sHeader, sPayload, prvKey);ultraSecureToken = sJWT;
One difference which I can clearly see is that for the signature generation function
in the php end I am passing sha256
as the algorithm and in the JavaScript RS256
is passed.
I read about how sha256 is just a hashing algorithm and RS256 is used for encoding, but in all the libraries I found in php, they were internally passing sha256
only in the openssl_sign
function. And openssl_sign
doesn't have RS256 as an algorithm parameter.
So, firstly is there anywhere where I went wrong.
Secondly, is there a way we can generate a signature using RS256 in php.
PS : I am looking for solution in php.
I have found out that calculating sha256 in java is slow. For example, it is slower than python. I wrote two simple benchmarks that calculate sha256 of 1GB of zeroes. In both cases the result is the same and correct, but the python time is 5653ms and the java time is 8623ms(53% slower). The result is similar every time and this is an important difference for me.
How to make the calculation in java faster?
Benchmarks:
Java:
import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;public class BenchmarkSha256 { public static void main(String... args) throws NoSuchAlgorithmException { int size = 1024 * 1024; byte[] bytes = new byte[size]; MessageDigest md = MessageDigest.getInstance("SHA-256"); long startTime = System.nanoTime(); for (int i = 0; i < 1024; i++) md.update(bytes, 0, size); long endTime = System.nanoTime(); System.out.println(String.format("%1$064x", new java.math.BigInteger(1, md.digest()))); System.out.println(String.format("%d ms", (endTime - startTime) / 1000000)); }}
Python:
#!/usr/bin/env pythonimport hashlibimport timesize = 1024 * 1024bytes = bytearray(size)md = hashlib.sha256()startTime = time.time()for i in range(0, 1024): md.update(bytes)endTime = time.time()print "%s\n%d ms" % (md.hexdigest(), (endTime - startTime) * 1000)
results:
~> java BenchmarkSha25649bc20df15e412a64472421e13fe86ff1c5165e18b2afccf160d4dc19fe68a148623 ms~> python BenchmarkSha256.py 49bc20df15e412a64472421e13fe86ff1c5165e18b2afccf160d4dc19fe68a145653 ms
versions of java and python:
~> java -versionjava version "1.6.0_26"Java(TM) SE Runtime Environment (build 1.6.0_26-b03)Java HotSpot(TM) 64-Bit Server VM (build 20.1-b02, mixed mode)~> python --versionPython 2.7
The inverse question exists with no answer and a comment that I don't understand.
I am attempting to create a Base64 encoded HMAC-SHA1 signature for a pseudo OAuth authentication header for an API. I found a support document (requires authenticated access) that takes you through the evolution of creating the signature. I'm able to create the same data up until the final step which is to Base64 encode the hash.
The support document states that the HMAC-SHA1 signature is:
cb5acd2d3ef689a8fbec4d06c576371834689673
And I get:
CB5ACD2D3EF689A8FBEC4D06C576371834689673
The support document then states
From the hex result string in step 3, encode the value using Base64
and provides the following Base64 encoded result (58 characters):
Y2I1YWNkMmQzZWY2ODlhOGZiZWM0ZDA2YzU3NjM3MTgzNDY4OTY3Mw==
When I use Convert.ToBase64String()
to convert my signature I get (28 characters):
y1rNLT72iaj77E0GxXY3GDRolnM=
I'm stumped, I don't know if the support document is incorrect or if I'm doing something wrong. The fact that I'm generating a string that is 28 characters and the example is 56 is too interesting to ignore.
The comment in the aforementioned semi-duplicate question also stumps me. I don't see how the string "MDY" translates to any ascii or unicode digits that make sense to me - I don't understand how the comment author came to that conclusion.
The hex value is being encoded as text ("062..." == 0x30, 0x36, 0x32, ...) rather than as the large number it represents.
I have a program in C
, which calculates sha256
hash of input file. It is using the openSSL
library. Here is the core of the program:
#include <openssl/sha.h>SHA256_CTX ctx;unsigned char buffer[512];SHA256_Init(&ctx);SHA256_Update(&ctx, buffer, len);SHA256_Final(buffer, &ctx);fwrite(&buffer,32,1,stdout);
I need to change it to calculate sha512
hash instead.
Can I just (naively) change all the names of the functions from SHA256
to SHA512
, and then in the last step fwrite
64 bytes, instead of the 32
bytes ? Is that all, or do I have to make more changes ?
I often compute checksums of files downloaded from the Internet, using shasum
family of commands, without paying attention to the mode for reading. In particular, sha1sum
usually defaults to text mode for applications.
What is the difference between reading in text mode and binary mode, when checking checksums using sha1sum
?
~/Downloads$ sha1sum --helpUsage: sha1sum [OPTION]... [FILE]...Print or check SHA1 (160-bit) checksums.With no FILE, or when FILE is -, read standard input. -b, --binary read in binary mode -c, --check read SHA1 sums from the FILEs and check them --tag create a BSD-style checksum -t, --text read in text mode (default) -z, --zero end each output line with NUL, not newline, and disable file name escapingThe following five options are useful only when verifying checksums: --ignore-missing don't fail or report status for missing files --quiet don't print OK for each successfully verified file --status don't output anything, status code shows success --strict exit non-zero for improperly formatted checksum lines -w, --warn warn about improperly formatted checksum lines --help display this help and exit --version output version information and exitThe sums are computed as described in FIPS-180-1. When checking, the inputshould be a former output of this program. The default mode is to print aline with checksum, a space, a character indicating input mode ('*' for binary,' ' for text or where binary is insignificant), and name for each FILE.GNU coreutils online help: <https://www.gnu.org/software/coreutils/>Full documentation <https://www.gnu.org/software/coreutils/sha1sum>or available locally via: info '(coreutils) sha1sum invocation'
Hjem - Sitemap - Personvern - Lenker - Copyright © 2019 Cortex IT Ltd : Kontakt : admin @ cortexit.co.uk
Please note that by viewing our site you agree to our use of cookies (see Personvern for details). You will only see this message once.