In the supplementary comments for PHP's OpenSSL functions there's this snippet
function pem2der($pem_data) {
$begin = "CERTIFICATE-----";
$end = "-----END";
$pem_data = substr($pem_data, strpos($pem_data, $begin)+strlen($begin));
$pem_data = substr($pem_data, 0, strpos($pem_data, $end));
$der = base64_decode($pem_data);
return $der;
}
function der2pem($der_data) {
$pem = chunk_split(base64_encode($der_data), 64, "\n");
$pem = "-----BEGIN CERTIFICATE-----\n".$pem."-----END CERTIFICATE-----\n";
return $pem;
}
These functions aren't inverses. My test code:
$priv_key = ...;
print $priv; // dev data, of course
print der2pem (pem2der ($priv));
Prints
-----BEGIN PRIVATE KEY-----
MIIJQwIBADANBgkqhkiG9w0BAQEFAAS... (etc)
then
-----BEGIN CERTIFICATE-----
TEKEYMIIJQwIBADANBgkqhkiG9w0BAQEFA... (etc)
Note the second one has a TEKEY prefix. In hex that's 4c4284 which doesn't look significant.
Where did this come from?
These functions are only designed to handle certificates, not private keys. The reason the result is wrong is because the pem2der function is looking for the start of a certificate (CERTIFICATE----- from -----BEGIN CERTIFICATE-----). You're trying to decode a key starting with -----BEGIN PRIVATE KEY-----. The "TE KEY" part of the result comes from here: "-----BEGIN PRIVATE KEY-----" and is a result of the functions not handling that header so the substr calls return the wrong result.
In theory, the functions should be very easy to modify to process private key files though.
Related
In python, I extract modulus (n) and (e) from a public key like this:
#! /usr/bin/python3.5
# -*- coding: utf-8 -*-
import rsa
(pubkey, privkey) = rsa.newkeys(512)
dec_n = pubkey.n
dec_e = pubkey.e
In base64, the value of n and e are:
n:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACIGqijUcytyQLcEVxC5gK4HDx7Y_c5aMJt9OOoWDfzcrifmZr0-8Q1i_LPE-4fuBLlaPl6EmgSN2wlbF_svHZV
e:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAB
And I have the following public key:
-----BEGIN RSA PUBLIC KEY-----
MEgCQQCIGqijUcytyQLcEVxC5gK4HDx7Y/c5aMJt9OOoWDfzcrifmZr0+8Q1i/LP
E+4fuBLlaPl6EmgSN2wlbF/svHZVAgMBAAE=
-----END RSA PUBLIC KEY-----
I tried to generate the same public key in PHP. To do this, I read this post: openssl: how can i get public key from modulus
So I wrote this code:
require_once("/var/www/phpseclib/Crypt/RSA.php");
$n = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACIGqijUcytyQLcEVxC5gK4HDx7Y_c5aMJt9OOoWDfzcrifmZr0-8Q1i_LPE-4fuBLlaPl6EmgSN2wlbF_svHZV";
$e = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAB";
$rsa = new Crypt_RSA();
$modulus = new Math_BigInteger(base64_decode(urldecode($n)), 256);
$exponent = new Math_BigInteger(base64_decode(urldecode($e)), 256);
$rsa->loadKey(array('n' => $modulus, 'e' => $exponent));
$rsa->setPublicKey();
$pub_key = $rsa->getPublicKey();
print_r($pub_key);
But I got this public key:
-----BEGIN PUBLIC KEY-----
MFgwDQYJKoZIhvcNAQEBBQADRwAwRAI9AIgaqKNRzK3JAtwRXELmArgcPHthzlowm3046hYN/NyuJ+ZmvTxDWIs8Th+4EuVo+XoSaBI3bCVsWy8dlQIDAQAB
-----END PUBLIC KEY-----
The difference is caused by two factors: First, the public key is displayed in the Python-code in the PKCS1-format ([1] and [2]), and in the PHP-code in the X.509-format ([1] and [3]). Secondly, there is a bug in the Base64-encoding.
Base64-encoding: In the Python-code the Base64url-encoding was used and in the PHP-code only the standard Base64-encoding ([4]). Although the code with the Base64url-encoding isn't posted, this can be concluded from the characters - and _ occurring in the encoded data. To use Base64url-decoding (instead of Base64-decoding) in the PHP-code:
$modulus = new Math_BigInteger(base64_decode(urldecode($n)), 256);
must be replaced by:
$modulus = new Math_BigInteger(base64url_decode(urldecode($n)), 256);
with ([5]):
function base64url_decode( $data ){
return base64_decode( strtr( $data, '-_', '+/') . str_repeat('=', 3 - ( 3 + strlen( $data )) % 4 ));
}
And analogously also for the exponent.
The PHP-code thus returns the following public key:
-----BEGIN PUBLIC KEY-----
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAIgaqKNRzK3JAtwRXELmArgcPHtj9zlo
wm3046hYN/NyuJ+ZmvT7xDWL8s8T7h+4EuVo+XoSaBI3bCVsX+y8dlUCAwEAAQ==
-----END PUBLIC KEY-----
Note: The Base64url-decoding of modulus and exponent is hexadecimal:
modulus : 0000000000000000000000000000000000000000000000000000000000000000881aa8a351ccadc902dc115c42e602b81c3c7b63f73968c26df4e3a85837f372b89f999af4fbc4358bf2cf13ee1fb812e568f97a126812376c256c5fecbc7655
exponent: 000000000000000000000000000000000000000000010001
The padding with the many 0-values isn't necessary (apart from the sign-byte), contains no information and only increases the amount of data.
Format: The public key from the last step is identical in content and only differs in the format (X.509). The easiest way to show this is to additionally display the public key in the PKCS1-format with ([6]):
$pub_key = $rsa->getPublicKey(CRYPT_RSA_PUBLIC_FORMAT_PKCS1);
print($pub_key . "\n");
The public key in the PKCS1-format matches the key of the Python-code. Another possibility is the direct comparison of both keys in an ASN.1 editor, e.g. online ([7]).
By the way: To use the public key of the Python-code also in the PHP-code, it isn't necessary to take the detour via modulus and exponent. This is much easier possible with ([6]):
$rsa = new Crypt_RSA();
$keydata = "-----BEGIN RSA PUBLIC KEY-----\n
MEgCQQCIGqijUcytyQLcEVxC5gK4HDx7Y/c5aMJt9OOoWDfzcrifmZr0+8Q1i/LP
E+4fuBLlaPl6EmgSN2wlbF/svHZVAgMBAAE=
\n-----END RSA PUBLIC KEY-----";
$rsa->loadKey($keydata);
$rsa->setPublicKey();
$pub_key = $rsa->getPublicKey(CRYPT_RSA_PUBLIC_FORMAT_PKCS1);
print($pub_key . "\n");
$pub_key = $rsa->getPublicKey();
print($pub_key . "\n");
I need a little help.
I have a txt file with ecdsa public keys:
KEY_ID: 1
STATUS: VALID
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE+Y5mYZL/EEY9zGji+hrgGkeoyccK
D0/oBoSDALHc9+LXHKsxXiEV7/h6d6+fKRDb6Wtx5cMzXT9HyY+TjPeuTg==
-----END PUBLIC KEY-----
KEY_ID: 2
STATUS: VALID
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEaq6djyzkpHdX7kt8DsSt6IuSoXjp
WVlLfnZPoLaGKc/2BSfYQuFIO2hfgueQINJN3ZdujYXfUJ7Who+XkcJqHQ==
-----END PUBLIC KEY-----
KEY_ID: 3
STATUS: VALID
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEkvgJ6sc2MM0AAFUJbVOD/i34YJJ8
ineqTN+DMjpI5q7fQNPEv9y2z/ecPl8qPus8flS4iLOOxdwGoF1mU9lwfA==
-----END PUBLIC KEY-----
Now I need use key by ID in openssl_verify function.
My code:
$ecdsa_url_string = 'ECDSA_URL_STRING';
$stringToVerify = 'MY_STRING';
$ecdsa_keys = openssl_pkey_get_public(file_get_contents(PATH . '/ecdsa_keys.txt'));
$verified = openssl_verify($stringToVerify,pack("H*",$ecdsa_url_string ),$ecdsa_keys,"sha256");
if($verified === 1){
.....
}
Now my question/problem:
I also have the KEY_ID parameter in the return URL. When ID is 1, everything is OK because openssl_pkey_get_public function always returns only the ID 1 key.
Q1: I can not retrieve the other keys.
Q2: How do I specify which ID I want use for openssl_pkey_get_public?
I am ashamed of my ignorance and my stupidity.
Can anyone please help me with this?
thx
#Lawrence Cherone answer work for me.
Parse public keys from .txt file by php
my code:
$ecdsa_keys = file_get_contents(PATH . '/ecdsa_keys.txt');
$ecdsa_key_id = 'KEY_FROM_URL';
function getKeyById($id, $ecdsa_keys){
if(preg_match("~KEY_ID: $id\s+STATUS: VALID\s+(-{5}BEGIN PUBLIC KEY-{5}.+?-{5}END PUBLIC KEY-{5})~s", $ecdsa_keys, $match)){
$result = $match[1];
return $result;
}
return null;
}
if(($ecdsa_key = getKeyById($ecdsa_key_id, $ecdsa_keys)) !== null){
echo "<pre>".$ecdsa_key."</pre>";
} else {
echo "not found";
}
thx for help
I am trying to pass a string containing content of a RSA private key file to a PHP function ssh2_auth_pubkey_file:
My function looks like this: ssh2_auth_pubkey_file($connection, $ssh_auth_user, $ssh_auth_pub, $ssh_auth_priv, $ssh_auth_pass)
My problem is string $pubkeyfile in my function it is $ssh_auth_priv parameter. Everything works fine when I supply it with a pointer to file for example 'private.pem' but when I pass content of the file as string, I get error.
$ssh_auth_priv = 'private.pem'; works
I have tried:
$ssh_auth_priv = "-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEA6Gfo+vYawTT6afHSxBeMYx/s/5nsMHmdckTUj5wPNdG2LhPX
ywGGzyRB9qFAIJAaGmT9fPcgt/IIySOOqzvLGPXbdk15HW71FC8nVQmBYrQXWQnB
........
i3pcqQ2JwSgi9M6rVxDSHQrVVBhiXvAx7Q2B/TEf1BvhtxXdSntUUu63U13VGiOF
1J5RW3EjAeamKOEpaL75xQSSFZdqc7KUG6+cqejhyNkZ4oDk7x+gjuU=
-----END RSA PRIVATE KEY-----
"; does not work
$ssh_auth_priv = <<<KEY-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEA6Gfo+vYawTT6afHSxBeMYx/s/5nsMHmdckTUj5wPNdG2LhPX
ywGGzyRB9qFAIJAaGmT9fPcgt/IIySOOqzvLGPXbdk15HW71FC8nVQmBYrQXWQnB
........
i3pcqQ2JwSgi9M6rVxDSHQrVVBhiXvAx7Q2B/TEf1BvhtxXdSntUUu63U13VGiOF
1J5RW3EjAeamKOEpaL75xQSSFZdqc7KUG6+cqejhyNkZ4oDk7x+gjuU=
-----END RSA PRIVATE KEY-----
KEY; Heredoc does not work
I tried file_get_contents to a string, did not work.
My question is how to pass public key as a string, not a pointer to a file.
You will need to write the private key to a temp file and provide the name of that temp file to ssh2_auth_pubkey_file(), eg:
$session = ssh2_connect($host, $port, ['hostkey' => 'ssh-rsa']);
$tempPrivateKeyFileName = tempnam(sys_get_temp_dir(), 'id_rsa');
$fp = fopen($tempPrivateKeyFileName, 'wb+');
fwrite($fp, $yourPrivateKeyContents);
ssh2_auth_pubkey_file($session, $username, $pubkeyfile, $tempPrivateKeyFileName, $passphrase);
unlink($tempPrivateKeyFileName);
It's worth noting writing the private key to a file where it may be read by other processes may be risky depending on your application and environment. At the least you probably want to ensure the private key is encrypted with a passphrase. You may also wish to add a shutdown handler to ensure the temp file is removed if the process exits abnormally. eg:
register_shutdown_function(static function () use ($tempPrivateKeyFileName) {
if (file_exists($tempPrivateKeyFileName)) {
unlink($tempPrivateKeyFileName);
}
});
You can't pass a string for the public key filename argument, it has to be a filename. The function is defined that way.
i'm working on a site that invovles storing public/private RSA encrypted content, until recently i've been doing it all via javascript. I now need to be able to encrypt with public key in PHP, i've lost the last 6 hours to this problem. I'm willing to change libraries if needbe, but currently im trying this:
https://www.pidder.de/pidcrypt/?page=demo_rsa-encryption
keys:
$pub_key = "-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDVd/gb2ORdLI7nTRHJR8C5EHs4
RkRBcQuQdHkZ6eq0xnV2f0hkWC8h0mYH/bmelb5ribwulMwzFkuktXoufqzoft6Q
6jLQRnkNJGRP6yA4bXqXfKYj1yeMusIPyIb3CTJT/gfZ40oli6szwu4DoFs66IZp
JLv4qxU9hqu6NtJ+8QIDAQAB
-----END PUBLIC KEY-----";
$priv_key = "-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDVd/gb2ORdLI7nTRHJR8C5EHs4RkRBcQuQdHkZ6eq0xnV2f0hk
WC8h0mYH/bmelb5ribwulMwzFkuktXoufqzoft6Q6jLQRnkNJGRP6yA4bXqXfKYj
1yeMusIPyIb3CTJT/gfZ40oli6szwu4DoFs66IZpJLv4qxU9hqu6NtJ+8QIDAQAB
AoGADbnXFENP+8W/spO8Dws0EzJCGg46mVKhgbpbhxUJaHJSXzoz92/MKAqVUPI5
mz7ZraR/mycqMia+2mpo3tB6YaKiOpjf9J6j+VGGO5sfRY/5VNGVEQ+JLiV0pUmM
doq8n2ZhKdSd5hZ4ulb4MFygzV4bmH29aIMvogMqx2Gkp3kCQQDx0UvBoNByr5hO
Rl0WmDiDMdWa9IkKD+EkUItR1XjpsfEQcwXet/3QlAqYf+FE/LBcnA79NdBGxoyJ
XS+O/p4rAkEA4f0JMSnIgjl7Tm3TpNmbHb7tsAHggWIrPstCuHCbNclmROfMvcDE
r560i1rbOtuvq5F/3BQs+QOnOIz1jLslUwJAbyEGNZfX87yqu94uTYHrBq/SQIH8
sHkXuH6jaBo4lP1HkY2qtu3LYR2HuQmb1v5hdk3pvYgLjVsVntMKVibBPQJBAKd2
Dj20LLTzS4BOuirKZbuhJBjtCyRVTp51mLd8Gke9Ol+NNZbXJejNvhQV+6ad7ItC
gnDfMoRERMIPElZ6x6kCQQCP45DVojZduLRuhJtzBkQXJ4pCsGC8mrHXF3M+hJV+
+LAYJbXrQa4mre59wR0skgb6CwGg1siMrDzJgu3lmBB0
-----END RSA PRIVATE KEY-----";
/*
PHP code using phpseclib:"
$rsa = new Crypt_RSA();
//extract($rsa->createKey());
$plaintext = 'eKFqZhGXg/QzTKI9dbvamIxDSltVWoz73DSowr87ipWHRSqKBAE463VCrcNcDKyW
gleCanPtV4NQ0qEImhf2xpIHFPeaCc++a0u7ZhZF8vpn5E8AGz97lqs3o7XGwmm1
EUlCeHh3c6574wiUd93eWBWLhxQUJPK66V3CQT0SrEQ=
';
$plaintext=base64_decode($plaintext);
$rsa->loadKey($priv_key);
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$ciphertext = $rsa->decrypt($plaintext);
echo $ciphertext;
just echoing empty text, the plaintext variable is data encrypted via the pidcrypt website using those keys. why isnt this working? i've also tried running it through openssl:
$res = openssl_get_privatekey($priv_key);
/*
* NOTE: Here you use the returned resource value
*/
openssl_private_decrypt($plaintext,$newsource,$res);
echo "String decrypt : $newsource";
also did not work. i've read and everythibng says pidcrypt is openssl compatible. i just cant seem to figure it out.
This works for me:
<?php
include('Crypt/RSA.php');
$rsa = new Crypt_RSA();
$rsa->loadKey('-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDVd/gb2ORdLI7nTRHJR8C5EHs4RkRBcQuQdHkZ6eq0xnV2f0hk
WC8h0mYH/bmelb5ribwulMwzFkuktXoufqzoft6Q6jLQRnkNJGRP6yA4bXqXfKYj
1yeMusIPyIb3CTJT/gfZ40oli6szwu4DoFs66IZpJLv4qxU9hqu6NtJ+8QIDAQAB
AoGADbnXFENP+8W/spO8Dws0EzJCGg46mVKhgbpbhxUJaHJSXzoz92/MKAqVUPI5
mz7ZraR/mycqMia+2mpo3tB6YaKiOpjf9J6j+VGGO5sfRY/5VNGVEQ+JLiV0pUmM
doq8n2ZhKdSd5hZ4ulb4MFygzV4bmH29aIMvogMqx2Gkp3kCQQDx0UvBoNByr5hO
Rl0WmDiDMdWa9IkKD+EkUItR1XjpsfEQcwXet/3QlAqYf+FE/LBcnA79NdBGxoyJ
XS+O/p4rAkEA4f0JMSnIgjl7Tm3TpNmbHb7tsAHggWIrPstCuHCbNclmROfMvcDE
r560i1rbOtuvq5F/3BQs+QOnOIz1jLslUwJAbyEGNZfX87yqu94uTYHrBq/SQIH8
sHkXuH6jaBo4lP1HkY2qtu3LYR2HuQmb1v5hdk3pvYgLjVsVntMKVibBPQJBAKd2
Dj20LLTzS4BOuirKZbuhJBjtCyRVTp51mLd8Gke9Ol+NNZbXJejNvhQV+6ad7ItC
gnDfMoRERMIPElZ6x6kCQQCP45DVojZduLRuhJtzBkQXJ4pCsGC8mrHXF3M+hJV+
+LAYJbXrQa4mre59wR0skgb6CwGg1siMrDzJgu3lmBB0
-----END RSA PRIVATE KEY-----');
$ciphertext = 'B0xBiIroAo7xpHuDThpsAIAAlmlJtK1M0I4wGSJQuRMj5vy0g/+QeDYA4v+9Pl5m
R/eiXzmbNF/WrBNJkgTJQalXK8zLGXFs1YxSnpVazBIAZo+zrnwy6g0eZ4U6exEx
tVcU/ay+oRa+K0Rn03N29y3wi5Dy46hTSLQW12a7zLY=';
$ciphertext = 'wYevij6cVGuf6+675lL81dK4oQxxINn0ESWOIKDe76u9iAdzg5JwJGuiealOAKDY
GQPCzWFtY4i+xpC3lbxc01tuzwLqLDyc78d5ejmEMraPdToaX+Z7+naiabXUUQlg
PSxsVlpL9b5S6/kB9BVJK9aOYMBlonJEKs9IZKKuoVw=';
$ciphertext = str_replace(array("\r","\n",' '), '', $ciphertext);
$ciphertext = base64_decode($ciphertext);
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
echo base64_decode($rsa->decrypt($ciphertext));
That's using the default public / private key pair at https://www.pidder.de/pidcrypt/?page=demo_rsa-encryption . The ciphertext came from that page as well.
My guess as to what you're doing wrong: you're copy / pasting the text from the "Encrypted text" textbox but aren't removing the new line characters.
I'm trying to use the RSA implementation in phpseclib, I thought it would be easier to do the code once in a function and re-use the function.
When I've tried texting the code I get a error saying "decryption error"
Testing also made me realise that the ciphertext was different every time the code ran, so I'm clearly doing something wrong there!
The code for the functions is:
require_once "Crypt/RSA.php";
require_once "Crypt/AES.php";
//Function for encrypting with RSA
function rsa_encrypt($string, $public_key)
{
//Create an instance of the RSA cypher and load the key into it
$cipher = new Crypt_RSA();
$cipher->loadKey($public_key);
//Set the encryption mode
$cipher->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
//Return the encrypted version
return base64_encode($cipher->encrypt($string));
}
//Function for decrypting with RSA
function rsa_decrypt($string, $private_key)
{
//Create an instance of the RSA cypher and load the key into it
$cipher = new Crypt_RSA();
$cipher->loadKey($private_key);
//Set the encryption mode
$cipher->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
//Return the decrypted version
return $cipher->decrypt($string);
}
I've tried to test it using the following:
(The keys are just for testing so that's why its hardcoded).
It is in here that everytime the code is run that the value of $ciphertext changes everytime
//Private key
$private_key = "-----BEGIN RSA PRIVATE KEY----- MIICXAIBAAKBgQC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QAB -----END PUBLIC KEY-----";
//Test out the rsa encryption functions
$plaintext = "This is some plaintext to encrypt";
$ciphertext = rsa_encrypt($plaintext, $public_key);
$decipheredtext = rsa_decrypt($ciphertext, $private_key);
//Echo out results
echo sprintf("<h4>Plaintext for RSA encryption:</h4><p>%s</p><h4>After encryption:</h4><p>%s</p><h4>After decryption:</h4><p>%s</p>", $plaintext, $ciphertext, $decipheredtext);
EDIT:
Sample output is:
Plaintext for RSA encryption:
This is some plaintext we will encrypt
After encryption:
‘˜!ˆ_枦WýF¦E×9&ùš!´jéÓb÷á劀É7J+۪߯׎È㩨ɣ#(÷)ÃX„)÷O‘˱N#Øv«ÓÌPƒ¹—Âî!a¢¦a&Á½Á˜ö‰ºŠCðJ«vW{uAåoOÂXäÞ#÷ï`agÏ:OŒ
After decryption:
//Nothing is returned, it is blank here
I think GigaWatt's answer is the correct one. As for this:
Testing also made me realise that the ciphertext was different every
time the code ran, so I'm clearly doing something wrong there!
PKCS#1 padding adds random bytes so the ciphertext's will always be different. The PKCS#1 algorithm however knows when the plaintext ends and the random bytes begin so it's able to separate the two and return you the result you're wanting.
EDIT: I got it to work after I replaced the spaces in your keys with new lines. eg.
$private_key = "-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQCU+1bLfPmcY7qrF/dTbAtuJlv4R/FVc1WEH9HKU0jQjX/n/db9vz/x0i3te/bK
LNEcwUhBu+PWPnOt/qVURG9BUT6RsCRFUn0CyGiUKoy45o9K/mJAHmbrNtrUB6ckrYLF75Y50nUN
sBVHUDw8yQymmiOBT1gc/KM5s1xTz44LMwIDAQABAoGAGsiMtAyFu23ac0PdvOuhqm3O/vXAF0Ki
zxwBVURfxM6LfiOOcRPe5RSKGTW+Cl7AQVEmMlsa/LtBhLhQ9LNQ5L/4oTmRhCGiZZEmccAdjKsx
yMeaxkp+ZHvMxMKQNDgYg1CXqrCrpwwUuMUlA26tfxZ3xSFtFyDTaV9mgDQ1IGECQQCkX9Tum7D1
vQTwbhbYnu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