dta38159 2013-04-09 12:20
浏览 222
已采纳

Java和PHP对称加密(DES)

I need to have a basic/simple String encryption (i.e. low security is good enough, I just want to avoid that the communication is human readable) between my Java client application and the PHP server.

I opted thus for the symmetric DES encryption as it doesn't require any key exchange (same key will be used on client and on server) + it doesn't require Java Security Policy updates for longer keys. I also encode/decode Base64 as the data gets sent by a Http post.

Unfortunately my code doesn't work as decrypted text doesn't match input.

My Java code to encrypt:

SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
DESKeySpec keySpecEncrypt = new DESKeySpec(ParamsProvider.SERVER_ECRYPTION_SECRETKEY2); //Secret key is a byte[8] = {1, 2, 3, 4, 5, 6, 7, 8}
SecretKey keyEncrypt = keyFactory.generateSecret(keySpecEncrypt);

// Create the cipher 
Cipher desCipher = Cipher.getInstance("DES/CFB8/NoPadding");

// Initialize the cipher for encryption
desCipher.init(Cipher.ENCRYPT_MODE, keyEncrypt);

// Encrypt the text
byte[] textEncrypted = desCipher.doFinal(data.getBytes("UTF-8"));

//B64 encoding and return
byte[] encryptedB64ByteArray = (new org.apache.commons.codec.binary.Base64()).encode(textEncrypted);
return new String(encryptedB64ByteArray, "UTF8");

My PHP code to decrypt:

function decrypt($message) {
    $secret_key = array(1, 2, 3, 4, 5, 6, 7, 8);
    $decodedMsg = base64_decode($message);
    return base64_decode(mcrypt_decrypt(MCRYPT_DES, $key, $decodedMsg, MCRYPT_MODE_CFB));
}

My best guess is that my Java and PHP en/decryption parameters are not equal (e.g. CFB8 mode) but I have no clue on how to solve this.

Any help or hint would be greatly appreciated (I already lost a few hours on this one), Cheers, Thomas

  • 写回答

3条回答 默认 最新

  • doufu6130 2013-04-09 19:34
    关注

    Thanks for the hints.

    Unfortunately none of them worked out for me.

    I finally solved it based on this code: https://github.com/stevenholder/PHP-Java-AES-Encrypt

    Cheers, Thomas

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

报告相同问题?

悬赏问题

  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler