2011-01-14 139 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); 
}