简体   繁体   中英

Making UUID less than 30 chars

I have a UUID in my system that is 105cd680-a507-11e7-974e-b75d2751fd34 long.
The problem is that when I sent this UUID to a web service they only accept UUID's 30 chars long.

Any idea how to convert this to 30 chars and then be able to somehow convert it to same length UUID ?

Basically:

  1. My internal ID 105cd680-a507-11e7-974e-b75d2751fd34

  2. When I sent to the web service I want to convert to something 30 chars.

  3. When I get the response back I want that 30 char uuid to convert again as my internal ID 105cd680-a507-11e7-974e-b75d2751fd34

UUID is represented in a hex string. You can convert it into a base 64 format removing the hyphens without losing any information. When converting it back remember to reintroduce the four hypens and lower case the string, details about the format are here .

Here one online converter from hex to base64 and from base64 to hex

There is solution based on @Phoenix idea :

<?php
$g = "105cd680-a507-11e7-974e-b75d2751fd34";

$e = encodeGUID($g);
var_dump($e);
$ge = decodeGUID($e);
var_dump($ge);

function encodeGUID($g)
{
    $t = str_replace("-", "", $g);
    return base64_encode(pack("h*", $t));
}

function decodeGUID($g)
{
    $g = implode('', unpack("h*", base64_decode($g)));
    return substr($g, 0, 8) . '-' . substr($g, 8, 4) . '-' . substr($g, 12, 4)
        . '-' . substr($g, 16);
}

result will be:

string(24) "AcVtCFpwEX555HvVchXfQw=="
string(35) "105cd680-a507-11e7-974eb75d2751fd34"

So encoded string has 24 characters, if you want exactly 30 symbols you can pad it by symbol which is not in use for base64 encoding, let's say *

so code will look like:

<?php
$g = "105cd680-a507-11e7-974e-b75d2751fd34";

$e = encodeGUID($g);
var_dump($e);
$ge = decodeGUID($e);
var_dump($ge);

function encodeGUID($g)
{
    $t = str_replace("-", "", $g);
    $e = base64_encode(pack("h*", $t));
    return str_pad(base64_encode(pack("h*", $t)), 30, "*");
}

function decodeGUID($g)
{
    $g = implode('', unpack("h*", base64_decode(trim($g, ' *'))));
    return substr($g, 0, 8) . '-' . substr($g, 8, 4) . '-' . substr($g, 12, 4)
        . '-' . substr($g, 16);
}

And it will return:

string(30) "AcVtCFpwEX555HvVchXfQw==******"
string(35) "105cd680-a507-11e7-974eb75d2751fd34"

I don't see a anything wrong with just taking a substring of the UUID in your PHP code:

$uuid = "105cd680-a507-11e7-974e-b75d2751fd34";
$new_uid = substr($uuid, 0, 30);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM