dongxi1879 2014-01-31 16:45
浏览 45
已采纳

用PHP加密(mcrypt),在Ruby中解密(OpenSSL :: Cipher)

I'm working on a cross language project wrapping a ruby/Sinatra API in PHP to be consumed by another team. None of the information exposed by the API is sensitive, but we would prefer it not be easily accessible to a casual observer guessing the URL.

    private function generateSliceIDToken($key){
    $currentEpoch = time();
    $ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
    $iv = mcrypt_create_iv($ivSize, MCRYPT_RAND);
    $encryptedBytes = mcrypt_encrypt(
        MCRYPT_RIJNDAEL_128,
        $key,
        $currentEpoch.**Passcode**,
        MCRYPT_MODE_CBC, $iv
    );
    $ivAndEncryptedBytes = $iv . $encryptedBytes;

    return urlencode(urlencode(base64_encode($ivAndEncryptedBytes)));

The code above Encrypts a password and time stamp using mcrypt's RIJNDAEL implementation and encodes it to send off to the ruby API

if identifier.validate_token Base64.decode64(URI.unescape( URI.unescape(params[:token])))

Sinatra grabs it and decodes it

def validate_token(token)
  cipher = OpenSSL::Cipher::AES.new(128, 'CBC')
  cipher.decrypt
  cipher.key = **key**
  cipher.iv = token[0,16]

  plain = cipher.update(token[16..-1]) + cipher.final
  return plain[10,8] == **Passcode**
end

and passes it along to be decrypted

The problem is, the decryption fails with a 'Bad Decrypt' Error

I was lead to believe Mcrypt's RIJNDAEL and Cipher's AES were compatible, but is this assumption incorrect? Any help I can get one this would be most helpful.

  • 写回答

1条回答 默认 最新

  • dpn4073 2014-01-31 20:44
    关注

    I was lead to believe Mcrypt's RIJNDAEL and Cipher's AES were compatible, but is this assumption incorrect?

    You need to slightly tweak data being encoded to make it AES compatible. Data must be right padded, with character and amount depending of its current width:

    $encode = $currentEpoch.'**Passcode**';
    $len = strlen($encode);
    $pad = 16 - ($len % 16);
    $encode .= str_repeat(chr($pad), $pad);
    

    Also remember to have $key exactly 16 characters long. If it is shorter, ruby throws CipherError, while php pads key with null bytes. If it is longer, ruby uses only first 16 character but php pads it again, and uses last 16 characters.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 PointNet++的onnx模型只能使用一次
  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。