Skip to content

Instantly share code, notes, and snippets.

@tylermenezes
Created June 13, 2011 03:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tylermenezes/1022293 to your computer and use it in GitHub Desktop.
Save tylermenezes/1022293 to your computer and use it in GitHub Desktop.
PCBC Private-encrypted Signing Code
<?php
// You can generate keys with:
// key=$(openssl genrsa 128);echo "$key" | sed '{:q;N;s/\n/\\n/g;t q}';echo "$key" | openssl rsa -pubout | sed '{:q;N;s/\n/\\n/g;t q}' 2>/dev/null
/**
* Signs text with your private key, using PCBC.
* @author Tyler Menezes tylermenezes@gmail.com
*/
function Sign($toEncrypt){
$priv = openssl_pkey_get_private ("-----BEGIN RSA PRIVATE KEY-----\nMGQCAQACEQDEb/R70eBav9AmgH1GBvgZAgMBAAECEQCbMBNGyszjA2eKArxL3shN\nAgkA/O8v+KfoBc8CCQDG0XeJzSmFlwIJAIejmT0mheW/AghMu9+VEdfqtQIJAI16\nVWlE29KX\n-----END RSA PRIVATE KEY-----");
$toEncrypt = unpack('H*', $toEncrypt);
$toEncrypt = $toEncrypt[1];
$result = "";
while(strlen($toEncrypt)%16 != 0){
$toEncrypt .= "00";
}
$iv = "1234567812345678";
for($i = 0; $i < strlen($toEncrypt); $i+=16){
$p = substr($toEncrypt, $i, 16);
$x = $p ^ $iv;
if(!openssl_private_encrypt($x, $e, $priv, OPENSSL_NO_PADDING)){
throw new Exception(openssl_error_string());
}
$iv = $e ^ $p;
$result .= $e;
}
$result = unpack('H*', $result);
return $result[1];
}
/**
* Decrypts text with the UReddit public key, using PCBC.
* @author Tyler Menezes tylermenezes@gmail.com
*/
function Decrypt($toDecrypt){
$pub = openssl_pkey_get_public ("-----BEGIN PUBLIC KEY-----\nMCwwDQYJKoZIhvcNAQEBBQADGwAwGAIRAMRv9HvR4Fq/0CaAfUYG+BkCAwEAAQ==\n-----END PUBLIC KEY-----");
$toDecrypt = pack('H*', $toDecrypt);
$result = "";
$iv = "1234567812345678";
for($i = 0; $i < strlen($toDecrypt); $i+=16){
$e = substr($toDecrypt, $i, 16);
if(!openssl_public_decrypt($e, $x, $pub, OPENSSL_NO_PADDING)){
throw new Exception(openssl_error_string());
}
$p = $x ^ $iv;
$result .= $p;
$iv = $e ^ $p;
}
return pack('H*', $result);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment