<?php
function m24g($bArr, $modulus, $exponent) {
$publicKey = m23h($modulus, $exponent);
if (openssl_public_encrypt($bArr, $encryptedData, $publicKey, OPENSSL_PKCS1_PADDING)) {
return $encryptedData;
} else {
throw new Exception('Encryption failed: ' . openssl_error_string());
}
}
function m23h($modulus, $exponent) {
$modulus = gmp_import(hex2bin($modulus));
$exponent = gmp_import(hex2bin($exponent));
$rsa = [
'n' => gmp_strval($modulus, 16),
'e' => gmp_strval($exponent, 16),
];
$keyDetails = [
'kty' => 'RSA',
'n' => base64url_encode(hex2bin($rsa['n'])),
'e' => base64url_encode(hex2bin($rsa['e'])),
];
$pem = jwkToPem($keyDetails);
return $pem;
}
function base64url_encode($data) {
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}
function jwkToPem(array $jwk) {
$components = array(
'modulus' => base64url_decode($jwk['n']),
'publicExponent' => base64url_decode($jwk['e'])
);
$pem = "-----BEGIN PUBLIC KEY-----\n" .
chunk_split(base64_encode(createPublicKey($components)), 64, "\n") .
"-----END PUBLIC KEY-----\n";
return $pem;
}
function base64url_decode($data) {
return base64_decode(strtr($data, '-_', '+/'));
}
function createPublicKey($components) {
$modulus = $components['modulus'];
$publicExponent = $components['publicExponent'];
$sequence = new \FG\ASN1\Universal\Sequence();
$sequence->addChild(new \FG\ASN1\Universal\Integer($modulus));
$sequence->addChild(new \FG\ASN1\Universal\Integer($publicExponent));
$bitString = new \FG\ASN1\Universal\BitString($sequence->getBinary());
$outerSequence = new \FG\ASN1\Universal\Sequence();
$outerSequence->addChild(new \FG\ASN1\Universal\Sequence());
$outerSequence->addChild($bitString);
return $outerSequence->getBinary();
}
// Usage example
try {
$modulus = '113744026899259137585420519641795445506522315843166624587737104823905995993308512746423780711220091509477248711684203860721990053300351123157272120027826616226336455748256059222713368430653450802331260182403534624073361236909650202772541076543992882238347687352553725072578344237693663853480535496066481835463'; // Hexadecimal string of modulus
$exponent = '65537'; // Hexadecimal string of exponent
$dataToEncrypt = "912c1366-d5e0-c63a-e91d-7d6a495da509|147963";
$encryptedData = m24g($dataToEncrypt, $modulus, $exponent);
echo "Encrypted Data: " . base64_encode($encryptedData) . "\n";
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage() . "\n";
}
?>
preferences:
16.36 ms | 403 KiB | 5 Q