dtjo51649 2013-08-22 12:02
浏览 34
已采纳

在Objective C中签名字符串并在PHP中验证 - 不起作用

I am signing a string in ObjectiveC and verifying the generated signature in PHP.

lets say I sign a string "b1be1970fa802f43cdfa382bb3f3a524590b2170" using my privateKey with RSA_sign method (OpenSSL Lib) in ObjectiveC. And I get generated signature

I verify the signature in PHP using PublicKey with openssl_verify method.

Verification Fails

Any idea what might be wrong..

iOS Code:

NSString *handshakeChallengeStr = [NSString stringWithFormat:@"YjFiZTE5NzBmYTgwMmY0M2NkZmEzODJiYjNmM2E1MjQ1OTBiMjE3MA=="];
NSData *hcData = [NSData dataFromBase64String:handshakeChallengeStr];
const unsigned char *message = (const unsigned char *)[hcData bytes];
unsigned int message_length =strlen((const void *)message); //56

unsigned char *sig = NULL;
unsigned int sig_len = 0;

//Retriving PrivateKey
RSA *privKey = NULL;
EVP_PKEY *PrivateKey;
FILE *priv_key_file;
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
NSString *keyFilePath = [[paths objectAtIndex:0]stringByAppendingPathComponent:@"privateKey.pem"];

priv_key_file = fopen([keyFilePath UTF8String], "r");
PrivateKey = PEM_read_PrivateKey(priv_key_file, NULL, NULL, NULL);
privKey = EVP_PKEY_get1_RSA(PrivateKey);

sig = malloc(RSA_size(privKey));

int success = RSA_sign(NID_sha1, message, message_length, sig, &sig_len, privKey);
if(success == 1){
    NSLog(@"Signature Generated!!");
}

PHP Code:

$private = '-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDZz+ztvFV3qYu8
4NHErDVfVzfVhAVoCqQiCFBWpuNJk0xPgGIkwDkehhyIxCT1CD/GNYQSjpoFlfId
….
-----END PRIVATE KEY-----';

$public='-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2c/s7bxVd6mLvODRxKw1
X1c31YQFaAqkIghQVqbjSZNMT4BiJMA5HoYciMQk9Qg/xjWEEo6aBZXyHekc7w1d
……
-----END PUBLIC KEY-----';

$HandshakeStr = base64_decode('YjFiZTE5NzBmYTgwMmY0M2NkZmEzODJiYjNmM2E1MjQ1OTBiMjE3MA==');;

openssl_sign($HandshakeStr, $sig, $private);
  • 写回答

2条回答 默认 最新

  • dthy81285 2013-08-28 14:28
    关注

    PHP openssl_sign computes a signature for the specified data by using SHA1 for hashing (PHP: openssl_sign).

    OpenSSL RSA_sign signs the message digest m of size m_len (OpenSSL: RSA_sign(3))

    When you use the raw OpenSSL functions you have to do the hashing yourself:

        unsigned char message_digest[SHA_DIGEST_LENGTH];
        SHA1(message, message_length, message_digest);
        int success = RSA_sign(NID_sha1, message_digest, SHA_DIGEST_LENGTH, sig, &sig_len, privKey);
    

    By the way, use RSA verify - not every signature scheme is deterministic.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 fesafe材料库问题
  • ¥35 beats蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统