cryptico.js可以与openssl一起使用,但我们必须对它进行一些修改.
它不直接识别pem格式的公钥(使用openssl).我们必须在php端提取公钥的’n’和’e’部分:
$key = openssl_pkey_new(array(
'private_key_bits' => 1024,
'private_key_type' => OPENSSL_KEYTYPE_RSA,
'digest_alg' => 'sha256'
));
$detail = openssl_pkey_get_details($key);
$n = base64_encode($detail['rsa']['n']);
$e = bin2hex($detail['rsa']['e']);
另外,cryptico.js硬编码了公钥的’e’部分(参见api.js中publicKeyFromString的定义),所以我们需要解决这个问题:
my.publicKeyFromString = function(string)
{
var tokens = string.split("|");
var N = my.b64to16(tokens[0]);
var E = tokens.length > 1 ? tokens[1] : "03";
var rsa = new RSAKey();
rsa.setPublic(N, E);
return rsa
}
现在我们可以加密字符串:
var publicKey = "{$n}|{$e}",
encrypted = cryptico.encrypt("plain text", publicKey);
工作尚未完成. cryptico.encrypt的结果不仅仅是由RSA加密.实际上,它由两部分组合而成:一个由RSA加密的aes密钥,以及由AES用该密钥加密的明文密码.如果我们只需要RSA,我们可以修改my.encrypt:
my.encrypt = function(plaintext, publickeystring, signingkey)
{
var cipherblock = "";
try
{
var publickey = my.publicKeyFromString(publickeystring);
cipherblock += my.b16to64(publickey.encrypt(plaintext));
}
catch(err)
{
return {status: "Invalid public key"};
}
return {status: "success", cipher: cipherblock};
}
现在我们可以使用openssl解密密码:
$private = openssl_pkey_get_private("YOUR PRIVATE KEY STRING IN PEM");
// $encrypted is the result of cryptico.encrypt() in javascript side
openssl_private_decrypt(base64_decode($encrypted), $decrypted, $private);
// now $decrypted holds the decrypted plain text