好的,我已经编写了我的第一个函数式PHP扩展。它起作用了,但它只是概念的证明。现在我正在写另一本书,实际上是按老板的要求做的。
我想知道的是,从所有的php头上,这段代码是否有意义。我对诸如
emalloc
像这样,或者是有什么东西会在以后转过来咬我的手吗?
下面是其中一个函数的代码。它返回一个字符串的base64,该字符串也经过了blowfish加密。当调用函数时,它将提供两个字符串、要加密和编码的文本以及用于加密阶段的密钥。它不使用PHP自己的base64函数,因为此时,我不知道如何链接到它们。因为同样的原因,它没有使用PHP自己的mcrypt函数。相反,它链接到ssleay中
BF_ecb_encrypt
功能。
PHP_FUNCTION(Blowfish_Base64_encode)
{
char *psData = NULL;
char *psKey = NULL;
int argc = ZEND_NUM_ARGS();
int psData_len;
int psKey_len;
char *Buffer = NULL;
char *pBuffer = NULL;
char *Encoded = NULL;
BF_KEY Context;
int i = 0;
unsigned char Block[ 8 ];
unsigned char * pBlock = Block;
char *plaintext;
int plaintext_len;
int cipher_len = 0;
if (zend_parse_parameters(argc TSRMLS_CC, "ss", &psData, &psData_len, &psKey, &psKey_len) == FAILURE)
return;
Buffer = (char *) emalloc( psData_len * 2 );
pBuffer = Buffer;
Encoded = (char *) emalloc( psData_len * 4 );
BF_set_key( &Context, psKey_len, psKey );
plaintext = psData;
plaintext_len = psData_len;
for (;;)
{
if (plaintext_len--)
{
Block[ i++ ] = *plaintext++;
if (i == 8 )
{
BF_ecb_encrypt( Block, pBuffer, &Context, BF_ENCRYPT );
pBuffer += 8;
cipher_len += 8;
memset( Block, 0, 8 );
i = 0;
}
} else {
BF_ecb_encrypt( Block, pBuffer, &Context, BF_ENCRYPT );
cipher_len += 8;
break;
}
}
b64_encode( Encoded, Buffer, cipher_len );
RETURN_STRINGL( Encoded, strlen( Encoded ), 0 );
}
你会注意到我有两个
埃莫洛克
呼吁,为了
Encoded
为了
Buffer
. 只有
编码的
将返回给调用方,因此我担心缓冲区不会被释放。是这样吗?我要用malloc/免费的吗
缓冲区
?
如果还有其他明显的错误,我真的很感激知道。