Hash string in Java and validate it in PHP - java

I want to create a Java Application, which creates an user account.
After this, the user should be able to login on my website.
I need a Java method to generate a hash, which is supported by PHP.
In PHP I always used this function to generate a hash:
public function hashPassword($password){
$options = [
'cost' => 11,
];
$password."<br>";
$hash = password_hash($password, PASSWORD_BCRYPT, $options)."<br>";
return $hash;
}
How can I do this in Java, when ...
I use this in PHP, to validate the password
public function checkPassword($password, $hash){
if (password_verify($passwordFromPost, $hash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
}
PS: to generate the $hash, I use the first function.
If anything isn't correct, please correct my code, because I'm new in Java

Related

Java equivalent of PHP code return different base 64 encoding result

Java Code
completeStrBytes = new byte[2];
completeStrBytes[0] = (byte)(signatureLength>>>8); //signatureLength = 128
completeStrBytes[1] = (byte)signatureLength;
System.out.println(Base64.getEncoder().encodeToString(completeStrBytes));
output: AIA=
PHP Code
$firstPart = $signatureLength >> 8;
$secondPart = $signatureLength;
var_dump(base64_encode($firstPart . $secondPart));
output: string(8) "MDEyOA=="
I understand PHP string already treat as byte string.
May I know how to get java equivalent code in PHP? what's wrong in the PHP code?
Thanks in advance.
If the case of Java you're calculating base64 for 2-byte array { 0x00, 0x80 } . In case of php you're calculation base64 for a 4-character string "0128" (which you got when concatenated two numbers as strings).
You probably want to convert those numbers to chars first:
var_dump(base64_encode(chr($firstPart) . chr($secondPart))); // string(4) "AIA="
UPD
You also may want to use function pack to convert different data types into a string:
<?php
$signatureLength = 128;
var_dump(base64_encode(pack('n', $signatureLength))); // string(4) "AIA="
Note that there is also a base64url encoding, which is NOT the base64_encode() from PHP.
When you use PHP base64_encode() for example for JWT encoding/decoding, you will get into trouble.
So for your case try
var_dump(base64url_encode($firstPart . $secondPart));
function base64url_encode($data)
{
$b64 = base64_encode($data);
if ($b64 === false) {
return false;
}
$url = strtr($b64, '+/', '-_');
return rtrim($url, '=');
}
function base64url_decode($data, $strict = false)
{
$b64 = strtr($data, '-_', '+/');
return base64_decode($b64, $strict);
}

Synchronise my java apps with table user of fosuserbundle

I am trying to create a Desktop app (java) that points to the same database of my website (created using symfony 2), but I have the problem that I canot insert in the columns "password" and "salt" using the same encryption type sha512 generated by fosuserBundle, and I do not know how fosuserBundle generates the "salt" value.
My encoder is currently set as:
security:
encoders:
FOS\UserBundle\Model\UserInterface: sha512
Check FOS\UserBundle\Model\User __construct method:
public function __construct()
{
$this->salt = base_convert(sha1(uniqid(mt_rand(), true)), 16, 36);
$this->enabled = false;
$this->locked = false;
$this->expired = false;
$this->roles = array();
$this->credentialsExpired = false;
}
finally i find solution that make the field "salt" negligible in table fos_user is to make this methode just return the password
namespace Symfony\Component\Security\Core\Encoder;
protected function mergePasswordAndSalt($password, $salt)
{
if (empty($salt)) {
return $password;
}
if (false !== strrpos($salt, '{') || false !== strrpos($salt, '}')) {
throw new \InvalidArgumentException('Cannot use { or } in salt.');
}
return $password;
}

Splitting nested array sent from android to php

I am sending JSON Objects which contain converted ArrayLists. For the most part everything works fine except on the PHP page.
If I use:
if($_POST)
{
echo "Something was sent";
$obj = array();
$JSON_Entry = $_POST["Entry"];
$body = json_decode($JSON_Entry, true);
foreach ($body as $key => $value)
{
echo $value;
}
I get the response in android emulator logs;
Something was sent[SalesMade [id=0, product_description=Beer, qty=2, unit=3, total=6.0]]
But when I try to separate the array using:
foreach($value as $column => $row)
{
echo $row;
}
I get an Invalid argument supplied for foreach() error. Is it because I converted the ArrayList to a JSON object before posting?
First you have to json_decode() $value, then you can foreach() through it.

Add products from external site and make connection from Java with Magento

I want to add multiple product to cart from my external site.
I can add single product using this url :
http://localhost/magento/index.php/checkout/cart/add?product=2&qty=2
but for multiple I can’t use like this : http://localhost/magento/index.php/checkout/cart/add?product=2&qty=2&product=3&qty=4.
Is there any other way to do this ? My external source site is in JSP.
And I want to make connection to magento database using Java. So, Is there any tutorials or examples for Connection using Java? I know that SOAP & RPC can be used, but I don't know how to use.
Actually, I've written this code, into "CartController.php" file.
public function newAction() {
$cart = $this->_getCart();
try {
//getting list of products
$filter = new Zend_Filter_LocalizedToNormalized(array('locale' => Mage::app()->getLocale()->getLocaleCode()));
for ($i = 1; $i <= 4; $i++) {
echo '<br>';
$param = $_GET['product' . $i];
if (isset($param)) {
$param = explode("/", $param);
print_r($param);
$productId = $param[0];
$product = $this->addNewProduct($productId);
$quantity = $filter->filter($param[1]);
$params['product'] = $product;
$params['qty'] = $quantity;
$cart->addProduct($product);
}// if over
}//for over
$cart->save();
$message = $this->__('Added to Your Cart Successfully', Mage::helper('core')->escapeHtml());
$this->_getSession()->addSuccess($message);
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
$this->_redirect("checkout/cart/");
} catch (Mage_Core_Exception $e) {}
Now, we can add products, like this : http://localhost/magento/index.php/checkout/cart/new?product1=2/3&product2=3/3&product3=4/1
Where, in "product1=2/3" 2=>productId & 3=> it's quantity.
This code is working properly. But,I want to do this without modifying client's code.

How to get the embed HTML code for a video hosted in youtube programmatically

How to get the embed HTML code for a video hosted in youtube programmatically. What Java API is available
Use the YouTube Data API (there's pre-built GData client libraries, or you can do the HTTP/XML stuff yourself).
One of the <media:content/> entries will contain a URL for the embeddable SWF, if the video is embeddable.
Assuming you have the URL of the video, it's fairly simple to generate one. You need the end of the URL (the part after the /watch?v=, let's call it ID). To generate the iframe embed html, just place it in the appropriate place (in the src attribute, don't include the brackets):
<iframe title="YouTube video player" class="youtube-player" type="text/html" width="640"
height="390" src="http://www.youtube.com/embed/{ID}" frameborder="0"
allowFullScreen></iframe>
There are a couple of ways to get the v parameter from the URL. A regular expression would work.
Though the accepted answer works, if you want to do this programmatically you need the correct aspect ratio in order to generate optimal iframe dimensions for your video. I wrote the following php function that can generate a link for you on the fly. It uses the bash utility youtube-dl to get information about the video from any youtube link, so you'll need to make sure that's installed (apt-get install youtube-dl should work on Ubuntu or other debian flavors)
function getYoutubeEmbed($link, $size = [], $options = [], $privacy = false) {
$options += [
'rel' => true, // Show suggested videos when the video finishes.
'controls' => true, // Show player controls.
'showinfo' => true, // Show video title and player actions.
];
$json = json_decode(exec('youtube-dl -j --no-warnings ' . $link . ' 2>/dev/null'));
if ($json && !empty($id = $json->id) && !empty($width = $json->width) && !empty($height = $json->height)) {
$args = [];
foreach ($options as $option => $value) {
if (!$value) {
$args[] = $option . '=0';
}
}
if ($size) {
if (!empty($size['width']) && !empty($size['height'])) {
$width = $size['width'];
$height = $size['height'];
} else if (!empty($size['width'])) {
$height = ceil(($height * $size['width']) / $width);
$width = $size['width'];
} else if (!empty($size['height'])) {
$width = ceil(($width * $size['height']) / $height);
$height = $size['height'];
}
}
$url = ($privacy ? 'www.youtube-nocookie.com/embed/' : 'www.youtube.com/embed/') . $id . ($args ? '?' . implode('&',$args) : '');
$iframe = '<iframe width="' . $width . '" height="' . $height . '" src="//' . $url . '" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>';
return $iframe;
} else {
return false;
}
}
The function is fairly self explanatory but here's the breakdown:
At the minimum you need to supply a link for the first argument.
The second argument is an array of width, height or both. If you only specify one it will treat keep the default aspect ratio and calculate the other dimension for you (this is how I'd typically use it).
The third argument is an optional array of arguments which are documented in the function itself.
The fourt is an optional boolean argument for 'privacy' which is explained as:
Enable privacy-enhanced mode. When you turn on privacy-enhanced mode, YouTube won't store information about visitors on your website unless they play the video.
Usage example:
$link = 'https://www.youtube.com/watch?v=adAqQct3vRI';
echo getYoutubeEmbed($link, ['width' => 560], ['rel' => false]);
Output:
<iframe width="560" height="315" src="//www.youtube.com/embed/605gdJGdaPE?rel=0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>

Categories