我有一个使用证书对字符串签名的Java应用程序.它使用SHA1加密字符串.我正在尝试将代码转换为Delphi 2010,但我不知道如何使其与Java应用程序相同的工作方式(使用sha1).到目前为止,我发现了这一点:
它可以工作,但是不使用sha1,运行Java应用程序时会得到不同的结果.
Java代码
char[] pass = (char[]) null;
PrivateKey key = (PrivateKey) getKeyStore().getKey(alias, pass);
Certificate[] chain = getKeyStore().getCertificateChain(alias);
CertStore certsAndCRLs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(Arrays.asList(chain)), "BC");
X509Certificate cert = (X509Certificate) chain[0];
CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
gen.addSigner(key, cert, CMSSignedDataGenerator.DIGEST_SHA1);
gen.addCertificatesAndCRLs(certsAndCRLs);
CMSProcessable data = new CMSProcessableByteArray(conteudoParaAssinar);
CMSSignedData signed = gen.generate(data, true, "SunMSCAPI");
byte[] envHex = signed.getEncoded();
CertInfo certInfo = new CertInfo();
certInfo.Hash = new BigInteger(envHex).toString(16);
return certInfo;
德尔福代码
var
lSigner: TSigner;
lSignedData: TSignedData;
fs: TFileStream;
qt: integer;
ch: PChar;
msg : WideString;
content : string;
cert: TCertificate;
begin
cert := Self.GetCert;
content := 'test';
lSigner := TSigner.Create(self);
lSigner.Certificate := cert.DefaultInterface;
lSignedData := TSignedData.Create(self);
lSignedData.content := content;
msg := lSignedData.Sign(lSigner.DefaultInterface, false, CAPICOM_ENCODE_BASE64);
lSignedData.Free;
lSigner.Free;
编辑
基于Java代码,我是否应该以二进制格式获取证书信息,在其上应用sha1并将其转换为十六进制?这是正确的顺序,并且Java代码执行相同的操作吗?我可以在capicom tlb中看到一些SHA1常量以及一个哈希类,也许我应该使用这些类,但是我不知道如何.
解决方法:
我们在与Java Tomcat应用程序接口的某些delphi应用程序中使用DCPCrypt,并且能够获取SHA-256兼容的哈希值.我怀疑SHA1也很容易.
这是一个例子
function Sha256FileStreamHash(fs : TFileStream): String;
var
Hash: TDCP_sha256;
Digest: array[0..31] of byte; // RipeMD-160 produces a 160bit digest (20bytes)
i: integer;
s: string;
begin
if fs <> nil then
begin
fs.Seek(0, soFromBeginning);
Hash:= TDCP_sha256.Create(nil); // create the hash
try
Hash.Init; // initialize it
Hash.UpdateStream(fs,fs.Size); // hash the stream contents
Hash.Final(Digest); // produce the digest
s:= '';
for i:= 0 to 31 do
s:= s + IntToHex(Digest[i],2);
Result:= s; // display the digest
finally
Hash.Free;
end;
end;
end;
标签:translation,capicom,java,delphi
来源: https://codeday.me/bug/20191208/2090100.html