在 Java 和 PHP 之间加密/解密字符串

发布于 2024-12-25 06:13:46 字数 711 浏览 3 评论 0原文

我使用 AES 加密来加密和解密服务器端的 php 和 Android 应用程序(作为客户端)之间的字符串。

PHP 中的加密字符串是:

HaxRKnMxT24kCJWUXaVvqDHahzurJQK+sYA4lIHql/U=

在 Java 中是:

HaxRKnMxT24kCJWUXaVvqD/KMEkJTPTXEcCsHIYGX9TGtCNOHQcJyUURPk8qlgf3

我在 PHP 脚本中使用 phpseclib 来进行加密。

我在这里缺少什么?

相关的Java代码在这里

SecretKeySpec skeySpec = new SecretKeySpec(pad16(pass), "AES");
Cipher c = Cipher.getInstance("AES");
c.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] out = c.doFinal( input )

和PHP代码在这里:

$aes = new Crypt_AES();
$aes->setKey('password');
$encrypted_encoded_text =  base64_encode($aes->encrypt($plaintext));

I'm using AES encryption to encrypt and decrypt string between php on the server side and Android app (as client).

The encrypted string in PHP is:

HaxRKnMxT24kCJWUXaVvqDHahzurJQK+sYA4lIHql/U=

and in Java it's:

HaxRKnMxT24kCJWUXaVvqD/KMEkJTPTXEcCsHIYGX9TGtCNOHQcJyUURPk8qlgf3

I'm making use of phpseclib in the PHP script to do the encryption.

What am I missing here?

The relevant Java code here

SecretKeySpec skeySpec = new SecretKeySpec(pad16(pass), "AES");
Cipher c = Cipher.getInstance("AES");
c.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] out = c.doFinal( input )

And the PHP code here:

$aes = new Crypt_AES();
$aes->setKey('password');
$encrypted_encoded_text =  base64_encode($aes->encrypt($plaintext));

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

只有一腔孤勇 2025-01-01 06:13:46

为了使加密/解密能够跨不同语言工作,几乎不需要相同的东西。

  1. 加密算法(废话!)
  2. 密钥(废话,又来了!)
  3. 密钥大小
  4. 操作模式(ECB、CBC、CTR)
  5. 初始化向量(如果是 CBC,则不需要 ECB)
  6. 填充方案

    可能还有更多因素....

您确定所有这些在两种语言中都是相同的吗?如果是,那么您的加密/解密应该可以完美地工作,除非实现中存在错误(这种情况非常罕见但有可能)。

For the encryption/decryption to work across different languages, there are few things that needs to be the same.

  1. Encryption Algorithm (duh!)
  2. Key (duh, again!)
  3. Key Size
  4. Mode of Operation (ECB, CBC, CTR)
  5. Initialization Vector (If CBC, no need for ECB)
  6. Padding scheme

    and probably some more factors too....

Are you sure all those are the same across both the languages? If yes, then your encryption/decryption should work flawlessly unless there is a bug in the implementation (which is very very rare but possible).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文