Search in sources :

Example 56 with Base64.encodeBase64String

use of org.apache.commons.codec.binary.Base64.encodeBase64String in project azure-iot-sdk-java by Azure.

the class SignRequestTest method gettersAndSettersWork.

// Tests_SRS_HTTPHSMSIGNREQUEST_34_001: [This function shall save the provided keyId.]
// Tests_SRS_HTTPHSMSIGNREQUEST_34_002: [This function shall return the saved data.]
// Tests_SRS_HTTPHSMSIGNREQUEST_34_003: [This function shall save the provided data after base64 encoding it.]
// Tests_SRS_HTTPHSMSIGNREQUEST_34_004: [This function shall save the provided algo.]
@Test
public void gettersAndSettersWork() {
    // arrange
    final String expectedAlgoString = "some algorithm";
    final String expectedKeyId = "some key id";
    final byte[] expectedData = "some data".getBytes(StandardCharsets.UTF_8);
    final String expectedEncodedData = encodeBase64String(expectedData);
    new NonStrictExpectations() {

        {
            mockedMac.getAlgorithm();
            result = expectedAlgoString;
        }
    };
    SignRequest request = new SignRequest();
    // act
    request.setAlgo(mockedMac);
    request.setKeyId(expectedKeyId);
    request.setData(expectedData);
    // assert
    assertEquals(mockedMac, Deencapsulation.getField(request, "algo"));
    assertEquals(expectedKeyId, Deencapsulation.getField(request, "keyId"));
    assertArrayEquals(expectedEncodedData.getBytes(StandardCharsets.UTF_8), request.getData());
}
Also used : SignRequest(com.microsoft.azure.sdk.iot.device.hsm.parser.SignRequest) Base64.encodeBase64String(org.apache.commons.codec.binary.Base64.encodeBase64String) NonStrictExpectations(mockit.NonStrictExpectations) Test(org.junit.Test)

Example 57 with Base64.encodeBase64String

use of org.apache.commons.codec.binary.Base64.encodeBase64String in project azure-iot-sdk-java by Azure.

the class IotHubServiceSasTokenTest method constructor_good_case_flow_check.

// Tests_SRS_SERVICE_SDK_JAVA_IOTHUBSERVICESASTOKEN_12_002: [The constructor shall create a target uri from the url encoded host name)]
// Tests_SRS_SERVICE_SDK_JAVA_IOTHUBSERVICESASTOKEN_12_003: [The constructor shall create a string to sign by concatenating the target uri and the expiry time string]
// Tests_SRS_SERVICE_SDK_JAVA_IOTHUBSERVICESASTOKEN_12_004: [The constructor shall create a key from the shared access key signing with HmacSHA256]
// Tests_SRS_SERVICE_SDK_JAVA_IOTHUBSERVICESASTOKEN_12_005: [The constructor shall compute the final signature by url encoding the signed key]
// Tests_SRS_SERVICE_SDK_JAVA_IOTHUBSERVICESASTOKEN_12_006: [The constructor shall concatenate the target uri, the signature, the expiry time and the key name using the format: "SharedAccessSignature sr=%s&sig=%s&se=%s&skn=%s"]
@Test
public void constructor_good_case_flow_check() throws Exception {
    // Arrange
    String cryptoProvider = "HmacSHA256";
    String charset = "UTF-8";
    String iotHubName = "b.c.d";
    String hostName = "HOSTNAME." + iotHubName;
    String sharedAccessKeyName = "ACCESSKEYNAME";
    String policyName = "SharedAccessKey";
    String sharedAccessKey = encodeBase64String("1234567890abcdefghijklmnopqrstvwxyz=".getBytes(StandardCharsets.UTF_8));
    String connectionString = "HostName=" + hostName + ";SharedAccessKeyName=" + sharedAccessKeyName + ";" + policyName + "=" + sharedAccessKey;
    IotHubConnectionString iotHubConnectionString = IotHubConnectionStringBuilder.createConnectionString(connectionString);
    // Assert
    new Expectations() {

        URLEncoder urlEncoder;

        System system;

        final SecretKeySpec secretKeySpec;

        Mac mac;

        {
            URLEncoder.encode(hostName.toLowerCase(), String.valueOf(StandardCharsets.UTF_8));
            System.currentTimeMillis();
            // Semmle flags this as sensitive call, but it is a false positive since it is for test purposes
            // lgtm
            byte[] body = { 1 };
            secretKeySpec = new SecretKeySpec(body, cryptoProvider);
            Mac.getInstance(cryptoProvider);
        }
    };
    // Act
    IotHubServiceSasToken iotHubServiceSasToken = new IotHubServiceSasToken(iotHubConnectionString);
}
Also used : Expectations(mockit.Expectations) IotHubServiceSasToken(com.microsoft.azure.sdk.iot.service.auth.IotHubServiceSasToken) SecretKeySpec(javax.crypto.spec.SecretKeySpec) IotHubConnectionString(com.microsoft.azure.sdk.iot.service.IotHubConnectionString) Base64.encodeBase64String(org.apache.commons.codec.binary.Base64.encodeBase64String) IotHubConnectionString(com.microsoft.azure.sdk.iot.service.IotHubConnectionString) URLEncoder(java.net.URLEncoder) Mac(javax.crypto.Mac) Test(org.junit.Test)

Example 58 with Base64.encodeBase64String

use of org.apache.commons.codec.binary.Base64.encodeBase64String in project azure-iot-sdk-java by Azure.

the class ProvisioningServiceSasTokenTest method constructorCheckFormatSucceeded.

// Tests_SRS_PROVISIONING_SERVICE_SASTOKEN_12_002: [The constructor shall create a target uri from the url encoded host name)]
// Tests_SRS_PROVISIONING_SERVICE_SASTOKEN_12_003: [The constructor shall create a string to sign by concatenating the target uri and the expiry time string (one year)]
// Tests_SRS_PROVISIONING_SERVICE_SASTOKEN_12_004: [The constructor shall create a key from the shared access key signing with HmacSHA256]
// Tests_SRS_PROVISIONING_SERVICE_SASTOKEN_12_005: [The constructor shall compute the final signature by url encoding the signed key]
// Tests_SRS_PROVISIONING_SERVICE_SASTOKEN_12_006: [The constructor shall concatenate the target uri, the signature, the expiry time and the key name using the format: "SharedAccessSignature sr=%s&sig=%s&se=%s&skn=%s"]
// Tests_SRS_PROVISIONING_SERVICE_SASTOKEN_12_008: [The function shall return with the generated token]
@Test
public void constructorCheckFormatSucceeded() throws Exception {
    // Arrange
    String deviceProvisioningServiceName = "b.c.d";
    String hostName = "HOSTNAME." + deviceProvisioningServiceName;
    String sharedAccessKeyName = "ACCESSKEYNAME";
    String policyName = "SharedAccessKey";
    String sharedAccessKey = encodeBase64String("key".getBytes(StandardCharsets.UTF_8));
    String connectionString = "HostName=" + hostName + ";SharedAccessKeyName=" + sharedAccessKeyName + ";" + policyName + "=" + sharedAccessKey;
    ProvisioningConnectionString provisioningConnectionString = ProvisioningConnectionStringBuilder.createConnectionString(connectionString);
    // Act
    ProvisioningSasToken provisioningServiceSasToken = new ProvisioningSasToken(provisioningConnectionString);
    String token = provisioningServiceSasToken.toString();
    // Assert
    assertTrue(token.contains("SharedAccessSignature sr=hostname.b.c.d&sig="));
    assertTrue(token.contains("&se="));
    assertTrue(token.contains("&skn=ACCESSKEYNAME"));
}
Also used : ProvisioningConnectionString(com.microsoft.azure.sdk.iot.provisioning.service.auth.ProvisioningConnectionString) ProvisioningSasToken(com.microsoft.azure.sdk.iot.provisioning.service.auth.ProvisioningSasToken) Base64.encodeBase64String(org.apache.commons.codec.binary.Base64.encodeBase64String) ProvisioningConnectionString(com.microsoft.azure.sdk.iot.provisioning.service.auth.ProvisioningConnectionString) Test(org.junit.Test)

Example 59 with Base64.encodeBase64String

use of org.apache.commons.codec.binary.Base64.encodeBase64String in project azure-iot-sdk-java by Azure.

the class ProvisioningServiceSasTokenTest method constructorSucceeded.

// Tests_SRS_PROVISIONING_SERVICE_SASTOKEN_12_002: [The constructor shall create a target uri from the url encoded host name)]
// Tests_SRS_PROVISIONING_SERVICE_SASTOKEN_12_003: [The constructor shall create a string to sign by concatenating the target uri and the expiry time string]
// Tests_SRS_PROVISIONING_SERVICE_SASTOKEN_12_004: [The constructor shall create a key from the shared access key signing with HmacSHA256]
// Tests_SRS_PROVISIONING_SERVICE_SASTOKEN_12_005: [The constructor shall compute the final signature by url encoding the signed key]
// Tests_SRS_PROVISIONING_SERVICE_SASTOKEN_12_006: [The constructor shall concatenate the target uri, the signature, the expiry time and the key name using the format: "SharedAccessSignature sr=%s&sig=%s&se=%s&skn=%s"]
@Test
public void constructorSucceeded() throws Exception {
    // Arrange
    String cryptoProvider = "HmacSHA256";
    String charset = "UTF-8";
    String deviceProvisioningServiceName = "b.c.d";
    String hostName = "HOSTNAME." + deviceProvisioningServiceName;
    String sharedAccessKeyName = "ACCESSKEYNAME";
    String policyName = "SharedAccessKey";
    String sharedAccessKey = encodeBase64String("key".getBytes(StandardCharsets.UTF_8));
    String connectionString = "HostName=" + hostName + ";SharedAccessKeyName=" + sharedAccessKeyName + ";" + policyName + "=" + sharedAccessKey;
    ProvisioningConnectionString provisioningConnectionString = ProvisioningConnectionStringBuilder.createConnectionString(connectionString);
    // Assert
    new Expectations() {

        URLEncoder urlEncoder;

        System system;

        final SecretKeySpec secretKeySpec;

        Mac mac;

        {
            URLEncoder.encode(hostName.toLowerCase(), String.valueOf(StandardCharsets.UTF_8));
            System.currentTimeMillis();
            decodeBase64(sharedAccessKey.getBytes(charset));
            // Semmle flags this as sensitive call, but it is a false positive since it is for test purposes
            // lgtm
            byte[] body = { 1 };
            secretKeySpec = new SecretKeySpec(body, cryptoProvider);
            Mac.getInstance(cryptoProvider);
        }
    };
    // Act
    ProvisioningSasToken provisioningServiceSasToken = new ProvisioningSasToken(provisioningConnectionString);
}
Also used : Expectations(mockit.Expectations) ProvisioningConnectionString(com.microsoft.azure.sdk.iot.provisioning.service.auth.ProvisioningConnectionString) ProvisioningSasToken(com.microsoft.azure.sdk.iot.provisioning.service.auth.ProvisioningSasToken) SecretKeySpec(javax.crypto.spec.SecretKeySpec) Base64.encodeBase64String(org.apache.commons.codec.binary.Base64.encodeBase64String) ProvisioningConnectionString(com.microsoft.azure.sdk.iot.provisioning.service.auth.ProvisioningConnectionString) URLEncoder(java.net.URLEncoder) Mac(javax.crypto.Mac) Test(org.junit.Test)

Example 60 with Base64.encodeBase64String

use of org.apache.commons.codec.binary.Base64.encodeBase64String in project azure-iot-sdk-java by Azure.

the class ContractAPIHttpTest method requestNonceWithDPSTPMSucceeds.

// SRS_ContractAPIHttp_25_004: [This method shall retrieve the Url by calling 'generateRegisterUrl' on an object for UrlPathBuilder.]
// SRS_ContractAPIHttp_25_005: [This method shall prepare the PUT request by setting following headers on a HttpRequest 1. User-Agent : User Agent String for the SDK 2. Accept : "application/json" 3. Content-Type: "application/json; charset=utf-8".]
// SRS_ContractAPIHttp_25_006: [This method shall set the SSLContext for the Http Request.]
// SRS_ContractAPIHttp_25_008: [If service return a status as 404 then this method shall trigger the callback to the user with the response message.]
@Test
public void requestNonceWithDPSTPMSucceeds() throws IOException, ProvisioningDeviceClientException {
    // arrange
    final byte[] expectedPayload = "testByte".getBytes(StandardCharsets.UTF_8);
    ContractAPIHttp contractAPIHttp = createContractClass();
    prepareRequestExpectations();
    new NonStrictExpectations() {

        {
            mockedRequestData.getRegistrationId();
            result = TEST_REGISTRATION_ID;
            mockedRequestData.getEndorsementKey();
            result = TEST_EK;
            mockedRequestData.getStorageRootKey();
            result = TEST_SRK;
            mockedRequestData.getSslContext();
            result = mockedSslContext;
            mockedHttpRequest.send();
            result = mockedHttpResponse;
            ProvisioningDeviceClientExceptionManager.verifyHttpResponse(mockedHttpResponse);
            result = new ProvisioningDeviceHubException("test Exception");
            mockedHttpResponse.getStatus();
            result = 401;
            TpmRegistrationResultParser.createFromJson(new String(mockedHttpResponse.getBody()));
            result = mockedTpmRegistrationResultParser;
            mockedTpmRegistrationResultParser.getAuthenticationKey();
            result = encodeBase64String("some auth key".getBytes(StandardCharsets.UTF_8));
            new DeviceRegistrationParser(anyString, anyString, anyString, anyString);
            result = mockedDeviceRegistrationParser;
            mockedDeviceRegistrationParser.toJson();
            result = "some json";
        }
    };
    // act
    contractAPIHttp.requestNonceForTPM(mockedRequestData, mockedResponseCallback, null);
    // assert
    prepareRequestVerifications(HttpMethod.PUT, 0);
    new Verifications() {

        {
            new UrlPathBuilder(TEST_HOST_NAME, TEST_SCOPE_ID, ProvisioningDeviceClientTransportProtocol.HTTPS);
            times = 1;
            mockedUrlPathBuilder.generateRegisterUrl(TEST_REGISTRATION_ID);
            times = 1;
            mockedHttpRequest.setSSLContext(mockedSslContext);
            times = 1;
            mockedResponseCallback.run((ResponseData) any, null);
            times = 1;
        }
    };
}
Also used : UrlPathBuilder(com.microsoft.azure.sdk.iot.provisioning.device.internal.contract.UrlPathBuilder) Base64.encodeBase64String(org.apache.commons.codec.binary.Base64.encodeBase64String) DeviceRegistrationParser(com.microsoft.azure.sdk.iot.provisioning.device.internal.parser.DeviceRegistrationParser) ContractAPIHttp(com.microsoft.azure.sdk.iot.provisioning.device.internal.contract.http.ContractAPIHttp) Test(org.junit.Test)

Aggregations

Base64 (org.apache.commons.codec.binary.Base64)135 IOException (java.io.IOException)30 Test (org.junit.Test)29 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)12 InputStream (java.io.InputStream)11 HttpServletRequest (javax.servlet.http.HttpServletRequest)11 HttpServletResponse (javax.servlet.http.HttpServletResponse)11 Base64.encodeBase64String (org.apache.commons.codec.binary.Base64.encodeBase64String)11 ByteArrayInputStream (java.io.ByteArrayInputStream)10 HashMap (java.util.HashMap)10 SecretKeySpec (javax.crypto.spec.SecretKeySpec)9 MessageDigest (java.security.MessageDigest)8 File (java.io.File)7 UnsupportedEncodingException (java.io.UnsupportedEncodingException)7 URL (java.net.URL)7 Mac (javax.crypto.Mac)7 ServletException (javax.servlet.ServletException)7 X509Certificate (java.security.cert.X509Certificate)6 FileNotFoundException (java.io.FileNotFoundException)5 Signature (java.security.Signature)5