我在尝试使用 TripleDES 标准与请求加密字符串以用作令牌的支付处理器 (CCBill) 集成时遇到问题。我的应用程序是用 Java 编写的,我得到的结果不是支付处理器所期望的。
这里有一篇文章解决 Perl<->PHP 和 Perl<->ColdFusion,但没有针对 Java 的解决方案。
PERL 版本的代码如下所示:
#!/usr/bin/perl
# Perl Crypt Calamity (here be...something)
use strict;
use CGI;
use MIME::Base64;
use Crypt::TripleDES;
my $cgi = CGI->new();
my $param = $cgi->Vars();
$param->{key} = "bC5PEcLzvb+jY1FZWuP4pw50";
$param->{string} = "subscriptionId=0214288302000000207";
my $des = Crypt::TripleDES->new();
my $enc = $des->encrypt3($param->{string}, $param->{key});
$enc = encode_base64($enc);
$enc =~ s/\n//gs;
# resulting string (enc): yvT6h6jti9krth/BaA3cO3ABKult8N38fnEb24MS0BwnX+gc1NNgEA==
这是我的小 Java 类,它试图与 perl 脚本做同样的事情,但它返回一个完全不同的值:
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import org.apache.commons.codec.binary.Base64;
public class Encoder {
public String encrypt(String message, String encryptionKey) throws Exception {
// handle the key
SecretKey secretKey = null;
byte[] keyValueAsBytes = Arrays.copyOf(encryptionKey.getBytes("UTF-8"), 24);
DESedeKeySpec keySpec = new DESedeKeySpec(keyValueAsBytes);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
secretKey = keyFactory.generateSecret(keySpec);
// cipher
Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
// encode
byte[] plainText = message.getBytes("UTF-8");
byte[] encryptedText = cipher.doFinal(plainText);
return Base64.encodeBase64String(encryptedText);
}
public static void main(String[] args) throws Exception{
String secretKey = "bC5PEcLzvb+jY1FZWuP4pw50";
String message = "subscriptionId=0214288302000000207";
Encoder enc = new Encoder();
System.out.println(enc.encrypt(message, secretKey));
//returns:hw6JzwdvmjwORzmitXcQ6vsmskK6vtdIObu+KYiGW4D4DRwNGHEX2w==
}
}
任何建议和帮助将不胜感激。