2011-01-14 138 views
1

我想手动创建Web服务调用的签名标记。我从密钥库访问证书并访问证书的公钥。我现在有问题将RSAKeyValue转换为ds:CryptoBinary类型。代码返回了用于mudulus和exponent的Biginteger值,我正在寻找一种方法或算法将它们转换为八位组,然后转换为Bas64。这里是我的代码从BigInteger转换为八位字节?

RSAPublicKey rsaKey = (RSAPublicKey)certificate.getPublicKey(); 
customSignature.Modulus = rsaKey.getModulus(); 
customSignature.Exponent = rsaKey.getPublicExponent(); 

在Java中有没有解决方案可用于将整数转换为八位组表示?

回答

2

使用Apache公地编解码器框架试试下面的代码:

BigInteger modulus = rsaKey.getModulus(); 
org.apache.commons.codec.binary.Base64.encodeBase64String(modulus.toByteArray()); 
+0

谢谢,它很简单 – 2011-01-31 14:29:15

0

不幸的是,modulus.toByteArray()不直接映射到XML数字签名的ds:CryptoBinary类型,这也需要剥离前导零个字节。在做base64编码之前,你需要做类似以下的事情:

byte[] modulusBytes = modulus.toByteArray(); 
int numLeadingZeroBytes = 0; 
while(modulusBytes[numLeadingZeroBytes] == 0) 
    ++numLeadingZeroBytes; 
if (numLeadingZeroBytes > 0) { 
    byte[] origModulusBytes = modulusBytes; 
    modulusBytes = new byte[origModulusBytes.length - numLeadingZeroBytes]; 
    System.arraycopy(origModulusBytes,numLeadingZeroBytes,modulusBytes,0,modulusBytes.length); 
}