1
這是我的困境。我對閱讀Java代碼很熟悉,但不擅長編寫它。我有幾個亞馬遜文檔的例子,但我做錯了什麼。我正在使用Eclipse。我有AWS Java SDK,Apache Commons Codec &日誌記錄和Base64。我有我的項目中正確的類路徑中的所有代碼。如何使用Java和Eclipse爲Amazon API簽名REST請求?
我瞭解如何形成請求(元素順序,時間戳等),但我不知道如何將此信息發送給java代碼以創建簽名請求。因此,我將從文檔中使用的代碼開始。
代碼簽名:
import java.security.SignatureException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
/**
* This class defines common routines for generating
* authentication signatures for AWS requests.
*/
public class Signature {
private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
/**
* Computes RFC 2104-compliant HMAC signature.
* * @param data
* The data to be signed.
* @param key
* The signing key.
* @return
* The Base64-encoded RFC 2104-compliant HMAC signature.
* @throws
* java.security.SignatureException when signature generation fails
*/
public static String calculateRFC2104HMAC(String data, String key)
throws java.security.SignatureException
{
String result;
try {
// get an hmac_sha1 key from the raw key bytes
SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);
// get an hmac_sha1 Mac instance and initialize with the signing key
Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
mac.init(signingKey);
// compute the hmac on input data bytes
byte[] rawHmac = mac.doFinal(data.getBytes());
// base64-encode the hmac
result = Encoding.EncodeBase64(rawHmac);
} catch (Exception e) {
throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
}
return result;
}
}
代碼編碼:
/**
* This class defines common routines for encoding * data in AWS requests.
*/
public class Encoding {
/**
* Performs base64-encoding of input bytes.
*
* @param rawData * Array of bytes to be encoded.
* @return * The base64 encoded string representation of rawData.
*/
public static String EncodeBase64(byte[] rawData) {
return Base64.encodeBytes(rawData);
}
}
代碼我想出了籤要求:
import java.security.SignatureException;
public class SignatureTest {
/**
* @param args
* @throws SignatureException
*/
public static void main(String[] args) throws SignatureException {
// data is the URL parameters and time stamp to be encoded
String data = "<data-to-encode>";
// key is the secret key
String key = "<my-secret-key>";
Signature.calculateRFC2104HMAC(data, key);
}
}
起初,我得到相關的錯誤到類路徑,所以我將它們添加到我的項目中。現在,當我運行代碼時,我沒有遇到任何錯誤,也沒有響應,我只是返回到命令提示符。我知道這可能是一個簡單的解決方案。我花了一個星期的時間試圖找出答案,並沒有找到任何答案。有人能指引我朝着正確的方向嗎?
注意:由於尺寸的原因,我沒有在這裏包含Base64代碼,但在我的項目中確實存在這樣的代碼。