0
votes

I am using amazon s3 android low level sdk to upload a file and want to set md5 checksum to upload data.

1)Following is the code to create credentials:

 BasicAWSCredentials lAwsCredentials = new BasicAWSCredentials(
            Constants.ACCESS_KEY_ID, Constants.SECRET_KEY);

    AmazonS3Client lS3Client = new AmazonS3Client(lAwsCredentials);

2)Following is the code to calculate md5

public class MD5CheckSum {

public static byte[] createChecksum(String pFilepath) throws Exception {
    InputStream lFis = new FileInputStream(pFilepath);

    byte[] lBuffer = new byte[1024];
    MessageDigest lMessageDigest = MessageDigest.getInstance("MD5");

    int lNumRead;

    do {
        lNumRead = lFis.read(lBuffer);
        if (lNumRead > 0) {
            lMessageDigest.update(lBuffer, 0, lNumRead);
        }
    } while (lNumRead != -1);

    lFis.close();
    return lMessageDigest.digest();
}

public static String getMD5Checksum(String pFilepath) throws Exception {
    byte[] lBytes = createChecksum(pFilepath);
    return Base64.encodeToString(lBytes, Base64.DEFAULT);
}

}

3)Following is the code to set md5 using metadata:

try {
        lMd5 = MD5CheckSum.getMD5Checksum(pFile.getAbsolutePath());

        Log.v(TAG, "CheckSum:====" + lMd5);
    } catch (Exception lException) {
        lException.printStackTrace();
    }

    ObjectMetadata lObjectMetadata = new ObjectMetadata();
    if (lMd5 != null) {
        lObjectMetadata.setContentMD5(lMd5);

    }`
InitiateMultipartUploadResult mInitResponse = mS3Client.initiateMultipartUpload(new InitiateMultipartUploadRequest(mBucketName, mKeyName,
            lObjectMetadata);

But a exception is thrown by amazon when i set md5:

Caused by: com.amazonaws.services.s3.model.AmazonS3Exception: Anonymous users cannot initiate multipart uploads. Please authenticate. (Service: Amazon S3; Status Code: 403; Error Code: AccessDenied; Request ID: BA0C68FC884703FD), S3 Extended Request ID: re2sdbzf8MMqGAyrNQOoqYJ8EdXERoWE7cjG+UpfAtFuP5IeAbXmk6Riw+PX8Uw3Jcspn1rSQvI=

Is this the correct way to set md5?

Note: When md5 is not set(ie objectmetadata is not set) then upload works without any exception

1
It worked when i used Base64.encodeToString(lBytes, Base64.WRAP) instead of Base64.encodeToString(lBytes, Base64.DEFAULT);Max

1 Answers

1
votes

I have also faced this type of issue..

I fixed by adding Base64.DEFAULT instead of others such as WRAP and NO_WRAP.