How to use String.decodeBase64 method of com.github.kittinunf.fuel.util.Base64 class

Best Fuel code snippet using com.github.kittinunf.fuel.util.Base64.String.decodeBase64

RequestTest.kt

Source:RequestTest.kt Github

copy

Full Screen

1package com.github.kittinunf.fuel2import com.github.kittinunf.fuel.core.Encoding3import com.github.kittinunf.fuel.core.FuelManager4import com.github.kittinunf.fuel.core.Headers5import com.github.kittinunf.fuel.core.Method6import com.github.kittinunf.fuel.core.Request7import com.github.kittinunf.fuel.core.RequestFactory8import com.github.kittinunf.fuel.core.extensions.jsonBody9import com.github.kittinunf.fuel.test.MockHttpTestCase10import com.github.kittinunf.fuel.util.decodeBase6411import com.google.common.net.MediaType12import junit.framework.TestCase.assertEquals13import org.hamcrest.CoreMatchers.containsString14import org.hamcrest.CoreMatchers.equalTo15import org.hamcrest.CoreMatchers.notNullValue16import org.hamcrest.CoreMatchers.nullValue17import org.hamcrest.MatcherAssert.assertThat18import org.json.JSONArray19import org.json.JSONObject20import org.junit.Test21import org.mockserver.model.BinaryBody22import java.net.HttpURLConnection23import java.util.Random24import java.util.UUID25class RequestTest : MockHttpTestCase() {26 private val manager: FuelManager by lazy { FuelManager() }27 class PathStringConvertibleImpl(url: String) : RequestFactory.PathStringConvertible {28 override val path = url29 }30 class RequestConvertibleImpl(val method: Method, private val url: String) : RequestFactory.RequestConvertible {31 override val request = createRequest()32 private fun createRequest(): Request {33 val encoder = Encoding(34 httpMethod = method,35 urlString = url,36 parameters = listOf("foo" to "bar")37 )38 return encoder.request39 }40 }41 @Test42 fun testResponseURLShouldSameWithRequestURL() {43 mock.chain(44 request = mock.request().withMethod(Method.GET.value).withPath("/request"),45 response = mock.reflect()46 )47 val (request, response, result) = manager.request(Method.GET, mock.path("request")).response()48 val (data, error) = result49 assertThat(request, notNullValue())50 assertThat(response, notNullValue())51 assertThat(error, nullValue())52 assertThat(data, notNullValue())53 assertThat(request.url, notNullValue())54 assertThat(response.url, notNullValue())55 assertThat(request.url, equalTo(response.url))56 }57 @Test58 fun httpGetRequestWithDataResponse() {59 mock.chain(60 request = mock.request().withMethod(Method.GET.value).withPath("/request"),61 response = mock.reflect()62 )63 val (request, response, result) = manager.request(Method.GET, mock.path("request")).response()64 val (data, error) = result65 assertThat(request, notNullValue())66 assertThat(response, notNullValue())67 assertThat(error, nullValue())68 assertThat(data, notNullValue())69 val statusCode = HttpURLConnection.HTTP_OK70 assertThat(response.statusCode, equalTo(statusCode))71 }72 @Test73 fun httpGetRequestWithStringResponse() {74 mock.chain(75 request = mock.request().withMethod(Method.GET.value).withPath("/request"),76 response = mock.reflect()77 )78 val (request, response, result) = manager.request(Method.GET, mock.path("request")).responseString()79 val (data, error) = result80 assertThat(request, notNullValue())81 assertThat(response, notNullValue())82 assertThat(error, nullValue())83 assertThat(data, notNullValue())84 val statusCode = HttpURLConnection.HTTP_OK85 assertThat(response.statusCode, equalTo(statusCode))86 }87 @Test88 fun httpGetRequestWithImageResponse() {89 val decodedImage = "iVBORwKGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAClEQVQYV2NgYAAAAAMAAWgmWQAAAAASUVORK5CYII=".decodeBase64()90 val httpResponse = mock.response()91 .withHeader(Headers.CONTENT_TYPE, "image/png")92 .withBody(BinaryBody(decodedImage))93 mock.chain(94 request = mock.request().withMethod(Method.GET.value).withPath("/image"),95 response = httpResponse96 )97 val (request, response, result) = manager.request(Method.GET, mock.path("image")).responseString()98 val (data, error) = result99 assertThat(request, notNullValue())100 assertThat(response, notNullValue())101 assertThat(error, nullValue())102 assertThat(data, notNullValue())103 assertThat(response.toString(), containsString("bytes of image/png"))104 val statusCode = HttpURLConnection.HTTP_OK105 assertThat(response.statusCode, equalTo(statusCode))106 }107 @Test108 fun httpGetRequestWithBytesResponse() {109 val bytes = ByteArray(555)110 Random().nextBytes(bytes)111 mock.chain(112 request = mock.request().withMethod(Method.GET.value).withPath("/bytes"),113 response = mock.response().withBody(BinaryBody(bytes, MediaType.OCTET_STREAM))114 )115 val (request, response, result) = manager.request(Method.GET, mock.path("bytes")).responseString()116 val (data, error) = result117 assertThat(request, notNullValue())118 assertThat(response, notNullValue())119 assertThat(error, nullValue())120 assertThat(data, notNullValue())121 assertThat(response.toString(), containsString("Body : (555 bytes of application/octet-stream)"))122 val statusCode = HttpURLConnection.HTTP_OK123 assertThat(response.statusCode, equalTo(statusCode))124 }125 @Test126 fun httpGetRequestWithParameters() {127 val paramKey = "foo"128 val paramValue = "bar"129 mock.chain(130 request = mock.request().withMethod(Method.GET.value).withPath("/get"),131 response = mock.reflect()132 )133 val (request, response, result) = manager.request(Method.GET, mock.path("get"), listOf(paramKey to paramValue)).responseString()134 val (data, error) = result135 val string = data as String136 assertThat(request, notNullValue())137 assertThat(response, notNullValue())138 assertThat(error, nullValue())139 assertThat(data, notNullValue())140 val statusCode = HttpURLConnection.HTTP_OK141 assertThat(response.statusCode, equalTo(statusCode))142 assertThat(string, containsString(paramKey))143 assertThat(string, containsString(paramValue))144 }145 @Test146 fun httpPostRequestWithParameters() {147 val paramKey = "foo"148 val paramValue = "bar"149 mock.chain(150 request = mock.request().withMethod(Method.POST.value).withPath("/post"),151 response = mock.reflect()152 )153 val (request, response, result) = manager.request(Method.POST, mock.path("post"), listOf(paramKey to paramValue)).responseString()154 val (data, error) = result155 val string = data as String156 assertThat(request, notNullValue())157 assertThat(response, notNullValue())158 assertThat(error, nullValue())159 assertThat(data, notNullValue())160 val statusCode = HttpURLConnection.HTTP_OK161 assertThat(response.statusCode, equalTo(statusCode))162 assertThat(string, containsString(paramKey))163 assertThat(string, containsString(paramValue))164 }165 @Test166 fun httpPostRequestWithBody() {167 val foo = "foo"168 val bar = "bar"169 val body = "{ $foo: $bar }"170 // Reflect encodes the body as a string, and gives back the body as a property of the body171 // therefore the outer body here is the ey and the inner string is the actual body172 val correctBodyResponse = "\"body\":{\"type\":\"STRING\",\"string\":\"$body\",\"contentType\":\"text/plain; charset=utf-8\"}"173 mock.chain(174 request = mock.request().withMethod(Method.POST.value).withPath("/post"),175 response = mock.reflect()176 )177 val (request, response, result) = manager.request(Method.POST, mock.path("post"))178 .jsonBody(body)179 .responseString()180 val (data, error) = result181 val string = data as String182 assertThat(request, notNullValue())183 assertThat(request["Content-Type"].lastOrNull(), equalTo("application/json"))184 assertThat(response, notNullValue())185 assertThat(error, nullValue())186 assertThat(data, notNullValue())187 val statusCode = HttpURLConnection.HTTP_OK188 assertThat(response.statusCode, equalTo(statusCode))189 assertThat(string, containsString(correctBodyResponse))190 }191 @Test192 fun httpPutRequestWithParameters() {193 val paramKey = "foo"194 val paramValue = "bar"195 mock.chain(196 request = mock.request().withMethod(Method.PUT.value).withPath("/put"),197 response = mock.reflect()198 )199 val (request, response, result) = manager.request(Method.PUT, mock.path("put"), listOf(paramKey to paramValue)).responseString()200 val (data, error) = result201 val string = data as String202 assertThat(request, notNullValue())203 assertThat(response, notNullValue())204 assertThat(error, nullValue())205 assertThat(data, notNullValue())206 val statusCode = HttpURLConnection.HTTP_OK207 assertThat(response.statusCode, equalTo(statusCode))208 assertThat(string, containsString(paramKey))209 assertThat(string, containsString(paramValue))210 }211 @Test212 fun httpPatchRequestWithParameters() {213 val paramKey = "foo2"214 val paramValue = "bar2"215 mock.chain(216 request = mock.request().withMethod(Method.PATCH.value).withPath("/patch"),217 response = mock.reflect()218 )219 mock.chain(220 request = mock.request().withMethod(Method.POST.value).withHeader("X-HTTP-Method-Override", Method.PATCH.value).withPath("/patch"),221 response = mock.reflect()222 )223 val (request, response, result) = manager.request(Method.PATCH, mock.path("patch"), listOf(paramKey to paramValue)).responseString()224 val (data, error) = result225 val string = data as String226 assertThat(request, notNullValue())227 assertThat(response, notNullValue())228 assertThat(error, nullValue())229 assertThat(data, notNullValue())230 val statusCode = HttpURLConnection.HTTP_OK231 assertThat(response.statusCode, equalTo(statusCode))232 assertThat(string, containsString(paramKey))233 assertThat(string, containsString(paramValue))234 }235 @Test236 fun httpDeleteRequestWithParameters() {237 val paramKey = "foo"238 val paramValue = "bar"239 val foo = "foo"240 val bar = "bar"241 val body = "{ $foo : $bar }"242 val correctBodyResponse = "\"body\":{\"type\":\"STRING\",\"string\":\"$body\",\"contentType\":\"text/plain; charset=utf-8\"}"243 mock.chain(244 request = mock.request().withMethod(Method.DELETE.value).withPath("/delete"),245 response = mock.reflect()246 )247 val (request, response, result) = manager.request(Method.DELETE, mock.path("delete"), listOf(paramKey to paramValue))248 .jsonBody(body)249 .responseString()250 val (data, error) = result251 val string = data as String252 assertThat(request, notNullValue())253 assertThat(response, notNullValue())254 assertThat(error, nullValue())255 assertThat(data, notNullValue())256 val statusCode = HttpURLConnection.HTTP_OK257 assertThat(response.statusCode, equalTo(statusCode))258 assertThat(string, containsString(paramKey))259 assertThat(string, containsString(paramValue))260 assertThat(string, containsString(correctBodyResponse))261 }262 @Test263 fun httpHeadRequest() {264 val paramKey = "foo"265 val paramValue = "bar"266 mock.chain(267 request = mock.request().withMethod(Method.HEAD.value).withPath("/head"),268 response = mock.response().withStatusCode(HttpURLConnection.HTTP_OK)269 )270 val (request, response, result) = manager.request(Method.HEAD, mock.path("head"), listOf(paramKey to paramValue)).responseString()271 val (data, error) = result272 val string = data as String273 assertThat(request, notNullValue())274 assertThat(response, notNullValue())275 assertThat(error, nullValue())276 assertThat(data, notNullValue())277 assertThat(response.statusCode, equalTo(HttpURLConnection.HTTP_OK))278 assertThat(string, equalTo(""))279 }280 @Test281 fun httpOptionsRequest() {282 mock.chain(283 request = mock.request().withMethod(Method.OPTIONS.value).withPath("/options"),284 response = mock.response().withStatusCode(HttpURLConnection.HTTP_OK)285 )286 val (request, response, result) = manager.request(Method.OPTIONS, mock.path("options")).responseString()287 val (data, error) = result288 assertThat(request, notNullValue())289 assertThat(response, notNullValue())290 assertThat(error, nullValue())291 assertThat(data, notNullValue())292 assertThat(response.statusCode, equalTo(HttpURLConnection.HTTP_OK))293 }294 @Test295 fun httpTraceRequest() {296 mock.chain(297 request = mock.request().withMethod(Method.TRACE.value).withPath("/trace"),298 response = mock.response().withStatusCode(HttpURLConnection.HTTP_OK)299 )300 val (request, response, result) = manager.request(Method.TRACE, mock.path("trace")).responseString()301 val (data, error) = result302 assertThat(request, notNullValue())303 assertThat(response, notNullValue())304 assertThat(error, nullValue())305 assertThat(data, notNullValue())306 assertThat(response.statusCode, equalTo(HttpURLConnection.HTTP_OK))307 }308 @Test309 fun httpGetRequestUserAgentWithPathStringConvertible() {310 mock.chain(311 request = mock.request().withMethod(Method.GET.value).withPath("/user-agent"),312 response = mock.reflect()313 )314 val (request, response, result) = manager.request(Method.GET, PathStringConvertibleImpl(mock.path("user-agent"))).responseString()315 val (data, error) = result316 val string = data as String317 assertThat(request, notNullValue())318 assertThat(response, notNullValue())319 assertThat(error, nullValue())320 assertThat(data, notNullValue())321 assertThat(response.statusCode, equalTo(HttpURLConnection.HTTP_OK))322 assertThat(string, containsString("user-agent"))323 }324 @Test325 fun httpGetRequestWithRequestConvertible() {326 mock.chain(327 request = mock.request().withMethod(Method.GET.value).withPath("/get"),328 response = mock.reflect()329 )330 val (request, response, result) = manager.request(RequestConvertibleImpl(Method.GET, mock.path("get"))).responseString()331 val (data, error) = result332 assertThat(request, notNullValue())333 assertThat(response, notNullValue())334 assertThat(error, nullValue())335 assertThat(data, notNullValue())336 assertThat(response.statusCode, equalTo(HttpURLConnection.HTTP_OK))337 }338 @Test339 fun httpPatchRequestWithRequestConvertible() {340 val paramKey = "foo"341 val paramValue = "bar"342 mock.chain(343 request = mock.request().withMethod(Method.PATCH.value).withPath("/patch"),344 response = mock.reflect()345 )346 // HttpUrlConnection doesn't support patch347 mock.chain(348 request = mock.request().withMethod(Method.POST.value).withHeader("X-HTTP-Method-Override", Method.PATCH.value).withPath("/patch"),349 response = mock.reflect()350 )351 val (request, response, result) = manager.request(Method.PATCH, PathStringConvertibleImpl(mock.path("patch")), listOf(paramKey to paramValue)).responseString()352 val (data, error) = result353 assertThat(request, notNullValue())354 assertThat(response, notNullValue())355 assertThat(error, nullValue())356 assertThat(data, notNullValue())357 assertThat(response.statusCode, equalTo(HttpURLConnection.HTTP_OK))358 }359 @Test360 fun httpPostRequestWithRequestConvertibleAndOverriddenParameters() {361 val paramKey = "foo"362 val paramValue = "xxx"363 mock.chain(364 request = mock.request().withMethod(Method.POST.value).withPath("/post"),365 response = mock.reflect()366 )367 val (request, response, result) = manager.request(Method.POST, mock.path("post"), listOf(paramKey to paramValue)).responseString()368 val (data, error) = result369 val string = data as String370 assertThat(request, notNullValue())371 assertThat(response, notNullValue())372 assertThat(error, nullValue())373 assertThat(data, notNullValue())374 val statusCode = HttpURLConnection.HTTP_OK375 assertThat(response.statusCode, equalTo(statusCode))376 assertThat(string, containsString(paramKey))377 assertThat(string, containsString(paramValue))378 }379 @Test380 fun httpGetParameterArrayWillFormCorrectURL() {381 val lionel = "Lionel Ritchie"382 val list = arrayOf("once", "Twice", "Three", "Times", "Lady")383 val params = listOf("foo" to list, "bar" to lionel)384 mock.chain(385 request = mock.request().withMethod(Method.GET.value).withPath("/get"),386 response = mock.reflect()387 )388 val (response, error) = mock.path("get").httpGet(params).responseString().third389 val json = JSONObject(response)390 val query = json.getJSONObject("query")391 assertThat(error, nullValue())392 assertEquals(JSONArray("[\"$lionel\"]").toString(), query.getJSONArray("bar").toString())393 assertEquals(list.toList(), query.getJSONArray("foo[]").map { it.toString() })394 }395 @Test396 fun tagRequest() {397 val t1 = "tag"398 val t2 = 5399 val t3 = UUID.randomUUID()400 val (req, _) = mock.path("get").httpGet().tag(t1).tag(t2).tag(t3).response()401 assertThat(req.getTag(String::class), equalTo(t1))402 assertThat(req.getTag(Int::class), equalTo(t2))403 assertThat(req.getTag(UUID::class), equalTo(t3))404 val (anotherReq, _) = mock.path("get").httpGet().response()405 assertThat(anotherReq.getTag(String::class), nullValue())406 }407}...

Full Screen

Full Screen

TokenAuthenticationTests.kt

Source:TokenAuthenticationTests.kt Github

copy

Full Screen

1package gov.cdc.prime.router.tokens2import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper3import com.github.kittinunf.fuel.util.decodeBase644import gov.cdc.prime.router.CovidSender5import gov.cdc.prime.router.CustomerStatus6import gov.cdc.prime.router.Sender7import io.jsonwebtoken.Claims8import io.jsonwebtoken.JwsHeader9import io.jsonwebtoken.SignatureAlgorithm10import io.jsonwebtoken.SigningKeyResolverAdapter11import io.jsonwebtoken.io.Decoders12import io.jsonwebtoken.io.Encoders13import io.jsonwebtoken.security.Keys14import io.mockk.clearAllMocks15import io.mockk.every16import io.mockk.mockkObject17import org.junit.jupiter.api.BeforeEach18import java.math.BigInteger19import java.security.Key20import java.time.OffsetDateTime21import java.util.Date22import java.util.UUID23import javax.crypto.SecretKey24import kotlin.test.Test25import kotlin.test.assertEquals26import kotlin.test.assertFails27import kotlin.test.assertFalse28import kotlin.test.assertNotNull29import kotlin.test.assertNull30import kotlin.test.assertTrue31val exampleRsaPrivateKeyStr = """32 {33 "p": "7IICXiUlkefia-wDH9asy9Tbbinjr01HQmD-2uEz6EHEShu4ZwMkH6DmK-3AAfiazdjO9Nkl-aZQH9lsuI5FVpFzCIF4ljkJDpCJCXlARXdsLpO2mnZsIQ7ZF26evFT0hhG-C2WQ2ESb1vs0aW6Y6-x3K7FU6jQZEdRibDxSr3s",34 "kty":"RSA",35 "q":"1Mf_IShokWL0STqB8NBi-4ajcacmflXFMro8mhf2BTNoHXkpO_i9oZfX4ll6t_uVCEERhevUS93kxsV8DQI4vfi3915GZ5EH1sBGrrxsC8CDwVZQgNeCszLx51rXJhqFb4UdKxzQIATZCKAEqzHV2A9kiJ_aHGNVooBUYg-li9k",36 "d":"XIhGKq42y5XXDqBr8JARwN_ImLHs2568MjaMDp-Zj_ugvlPfxvCTE0ZwPbX53iIyVyQw9hbPJt1p3qB5b5WTmICv3WJjgWrRgRqtchuvavOUeC-W4zstzzvFKBfLKS-zJ23Zd07lXGCDZWyMZ30e9t1hxWJDpsr1agTpyYdHcw1yq2r-gLvllePEqgQCJG_s3wropaWklRza_ar6eVqqBaWmIch86saeOh0yw6pCMO_0TQg9PJIZ7C71j1yYytxQnjUpb5ugLFtaq9jax2y7dGDbUeAjxxmhw23IrV4qFNyH-1XNBL2MYlCGhC2BL7L6LGYnEBmuBxEsVkBuWHNE8Q",37 "e":"AQAB",38 "kid":"8711e745-77e6-49af-bde3-65dc61fc0706",39 "qi":"2zoetnmGAOWT3N8hIXIpZwETEhx4yllO_og_hI4u0gX3vxizHPu2nNxskBVZ4dE4I_31pHDwrqB5vASnl4tmBaeYvh-F0sTZVzgfecySD67It5zUY9wg2oVkfl_7iNIVJx7OxALZxXeGmHupsbzFzQ79hmgKrG5ohvI8cF_nqKs",40 "dp":"G3DqPWop9cfl6Ye0xRjva6cC3sFVfZ2Fyxnd-B9xGl2nHMIinzEqG9FbY3VudcwWihPBz37yfQji-w8LIk6_lM_DfRUonKV5e4shm0vKPUUh9DWHVlyvJxbF8YYQPOHOjU-5sTDToYQ0YLk8147Rh24kVZl5tMLetcbitJQ7M8k",41 "dq":"cEglOkMPgwC7tdS48vGT-fSfVP8GUg5CpDUge5P_T9lDrKHd_3aP4rC0zA25s1J_3z4u2AONIIe0DKvzfQ3aEW0o7tEBx-8BOvJ1mgl13nG1VRWOH58ZqiRNAG-wLrw6A5IzxSdMMEk-mc2PCSOgG4Zr36iyuN42Ny0O2jw1eGk",42 "n":"xJRuufBk_axjyO1Kpy5uwmnAY0VUhCzG8G4OiDVgnaXeLMzj91bcQdYOMQ_82PTGrUbck3qSFXbug_Ljj8NZDT0J1ZSKv8Oce-GdkeNzA5W9yvChvorGotAUWMS7_EXXxz8mjlrwu6kyKfCpuJAMg5VrZaYA0nAlv-e7zoRE9pQ0VHNrEaj6Uikw3M02oVHUNiRtL5Y5tYyz_yRBauVLPdHf5Yf-cZeO2x02qFSGcl_2EzWZcGb6PkQZ_9QeOq_iJ9h-NU_wb9lnbebnBhPGAyc1-_9vnFlFzkH2lt0BVtfhW0E4ieKkntbC0QFxNu91Gf4jfFmsOAsCf3UpVqWIQw"43 }44""".trimIndent()45// corresponding public key to above.46val exampleKeyId = "11209921-860e-4b6d-8d7e-adc8778e1c6c"47val exampleRsaPublicKeyStr = """48 {49 "kty":"RSA",50 "kid":"$exampleKeyId",51 "n":"xJRuufBk_axjyO1Kpy5uwmnAY0VUhCzG8G4OiDVgnaXeLMzj91bcQdYOMQ_82PTGrUbck3qSFXbug_Ljj8NZDT0J1ZSKv8Oce-GdkeNzA5W9yvChvorGotAUWMS7_EXXxz8mjlrwu6kyKfCpuJAMg5VrZaYA0nAlv-e7zoRE9pQ0VHNrEaj6Uikw3M02oVHUNiRtL5Y5tYyz_yRBauVLPdHf5Yf-cZeO2x02qFSGcl_2EzWZcGb6PkQZ_9QeOq_iJ9h-NU_wb9lnbebnBhPGAyc1-_9vnFlFzkH2lt0BVtfhW0E4ieKkntbC0QFxNu91Gf4jfFmsOAsCf3UpVqWIQw",52 "e":"AQAB"53 }54""".trimIndent()55val differentRsaPublicKeyStr = """56 {57 "kty":"RSA",58 "kid":"$exampleKeyId",59 "alg":"RS256",60 "n": "0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw",61 "e":"AQAB"62 }63""".trimIndent()64class TokenAuthenticationTests {65 private val sender = CovidSender(66 "foo",67 "bar",68 Sender.Format.CSV,69 CustomerStatus.INACTIVE,70 "mySchema",71 keys = null72 )73 private val tokenAuthentication = TokenAuthentication()74 private val jtiCache = MemoryJtiCache()75 // return the hardcoded public key used with this test. This is the Sender's public key.76 class UseTestKey(private val rsaPublicKeyStr: String) : SigningKeyResolverAdapter() {77 override fun resolveSigningKey(jwsHeader: JwsHeader<*>?, claims: Claims): Key {78 val jwk = jacksonObjectMapper().readValue(rsaPublicKeyStr, Jwk::class.java)79 return jwk.toRSAPublicKey()80 }81 }82 // return a ReportStream secret, used by ReportStream to sign a short-lived token83 class GetTestSecret : ReportStreamSecretFinder {84 private val TOKEN_SIGNING_KEY_ALGORITHM = SignatureAlgorithm.HS38485 // Good for testing: Each time you create a new GetTestSecret() obj, its a totally new secret.86 private val tokenSigningSecret = this.generateSecret()87 override fun getReportStreamTokenSigningSecret(): SecretKey {88 return Keys.hmacShaKeyFor(Decoders.BASE64.decode(tokenSigningSecret))89 }90 private fun generateSecret(): String {91 return Encoders.BASE64.encode(Keys.secretKeyFor(TOKEN_SIGNING_KEY_ALGORITHM).encoded)92 }93 }94 @BeforeEach95 fun reset() {96 clearAllMocks() // If using Companion object mocks, you need to be sure to clear between tests97 }98 @Test99 fun `test reading in Keys`() {100 // This really is a test of Jwk.kt, but I need the key pair here, and didn't101 // feel like keeping two copies of it.102 //103 // 1. Public104 // convert to our obj in two steps, to simulate reading from our db, into our Jwk obj first.105 val jwk = jacksonObjectMapper().readValue(exampleRsaPublicKeyStr, Jwk::class.java)106 val rsaPublicKey = jwk.toRSAPublicKey()107 assertNotNull(rsaPublicKey)108 assertEquals("RSA", rsaPublicKey.algorithm)109 assertEquals(BigInteger(jwk.e?.decodeBase64()), rsaPublicKey.publicExponent)110 // 2. Private. Again, two step conversion instead of calling Jwk.generateRSAPublicKey() directly111 // to be more like 'real life' where the data is coming from json in our Settings table, into Jwk obj.112 val jwk2 = jacksonObjectMapper().readValue(exampleRsaPrivateKeyStr, Jwk::class.java)113 val rsaPrivateKey = jwk2.toRSAPrivateKey()114 assertNotNull(rsaPrivateKey)115 assertEquals("RSA", rsaPrivateKey.algorithm)116 assertEquals(BigInteger(jwk2.d?.decodeBase64()), rsaPrivateKey.privateExponent)117 }118 @Test119 fun `test SenderUtils generateSenderToken`() {120 // Want to just keep one copy of my example keys, so I'm testing SenderUtils.generateSenderToken here.121 val jwk2 = jacksonObjectMapper().readValue(exampleRsaPrivateKeyStr, Jwk::class.java)122 val rsaPrivateKey = jwk2.toRSAPrivateKey()123 val senderToken = SenderUtils.generateSenderToken(124 sender,125 "http://asdf",126 rsaPrivateKey,127 exampleKeyId128 )129 // Must be a valid JWT130 assertEquals(3, senderToken.split(".").size)131 // Check that the public key correctly validates.132 assertTrue(TokenAuthentication().checkSenderToken(senderToken, UseTestKey(exampleRsaPublicKeyStr), jtiCache))133 }134 @Test135 fun `test createAccessToken and checkAccessToken happy path`() {136 val rslookup = GetTestSecret() // callback to look up the Reportstream secret, using to sign token.137 val token = tokenAuthentication.createAccessToken("foobar", rslookup)138 assertTrue(token.accessToken.isNotEmpty())139 // must expire later than now, but in less than 10 minutes140 val now: Int = (System.currentTimeMillis() / 1000).toInt()141 assertTrue(token.expiresAtSeconds >= now)142 assertTrue(token.expiresAtSeconds < now + 600)143 assertEquals("foobar", token.scope)144 assertEquals("bearer", token.tokenType)145 assertTrue(token.sub.startsWith("foobar_"))146 mockkObject(AuthenticationStrategy.Companion)147 every { AuthenticationStrategy.isLocal(any()) } returns false148 // Now read the token back in, and confirm its valid.149 val claims = tokenAuthentication.checkAccessToken(token.accessToken, "foobar", rslookup)150 // if claims is non-null then the sender's accessToken is valid.151 assertNotNull(claims)152 assertEquals(token.expiresAtSeconds, claims["exp"])153 assertEquals("foobar", claims["scope"])154 assertEquals(token.sub, claims["sub"])155 }156 /*157 * I thought it would be nice to show an end-to-end flow, as a happy path example.158 * This is a repeat of all the above tests, but all in one place.159 *160 * Vocabulary note:161 * There are two different tokens, which we're calling the SenderToken and the AccessToken.162 * Upon validation of a SenderToken, ReportStream will return a short duration AccessToken, which can be used163 * to call one of our endpoints, assuming a valid 'scope' for that endpoint.164 *165 * The details:166 * Step 1: The Sender signs a SenderToken using their private key.167 * Implemented by generateSenderToken()168 * Step 2: ReportStream checks the SenderToken using the corresponding public key it has in Settings.169 * Implemented by checkSenderToken()170 * Step 3: If validated, ReportStream returns a short-duration AccessToken, signed by the TokenSigningSecret171 * Implemented by createAccessToken()172 * Step 4: The Sender uses the AccessToken to make a request to a ReportStream endpoint.173 *174 * Step 5: The called ReportStream endpoint checks the validity of the AccessToken signature, etc.175 Implemented by checkAccessToken()176 */177 @Test178 fun `end to end happy path -- sender reqs token, rs authorizes, sender uses token, rs authorizes`() {179 val baseUrl = "http://localhost:7071/api/token"180 val privateKey = jacksonObjectMapper().readValue(exampleRsaPrivateKeyStr, Jwk::class.java).toRSAPrivateKey()181 // Step 1 - on the Sender side182 val senderToken = SenderUtils.generateSenderToken(sender, baseUrl, privateKey, exampleKeyId)183 // Step 2: ReportStream gets the token and checks it.184 val rslookup = GetTestSecret() // callback to look up the Reportstream secret, using to sign RS token.185 val senderLookup = UseTestKey(exampleRsaPublicKeyStr) // callback to lookup the sender's public key.186 val accessToken = if (TokenAuthentication().checkSenderToken(senderToken, senderLookup, jtiCache)) {187 // Step 3: Report stream creates a new accessToken188 tokenAuthentication.createAccessToken("myScope", rslookup)189 } else error("Unauthorized connection")190 // Step 4: Now pretend the sender has used the accessToken to make a request to reportstream...191 // Step 5: ... and ReportStream checks it:192 val claims = tokenAuthentication.checkAccessToken(accessToken.accessToken, "myScope", rslookup)193 // if claims is non-null then the sender's accessToken is valid.194 assertNotNull(claims)195 assertEquals(accessToken.expiresAtSeconds, claims["exp"])196 assertEquals("myScope", claims["scope"])197 }198 @Test199 fun `test mismatched Sender key`() {200 val privateKey = jacksonObjectMapper().readValue(exampleRsaPrivateKeyStr, Jwk::class.java).toRSAPrivateKey()201 val senderToken = SenderUtils.generateSenderToken(sender, "http://baz.quux", privateKey, exampleKeyId)202 val senderLookup = UseTestKey(differentRsaPublicKeyStr) // Its the wrong trousers!203 // false means we failed to validate the sender's jwt.204 assertFalse(TokenAuthentication().checkSenderToken(senderToken, senderLookup, jtiCache))205 }206 @Test207 fun `test junk Sender key`() {208 val privateKey = jacksonObjectMapper().readValue(exampleRsaPrivateKeyStr, Jwk::class.java).toRSAPrivateKey()209 val senderToken = SenderUtils.generateSenderToken(sender, "http://baz.quux", privateKey, exampleKeyId)210 val junkPublicKeyStr = """211 {212 "kty":"RSA",213 "kid":"$exampleKeyId",214 "n":"xJUNKRuufBk_axjyO1Kpy5uwmnAY0VUhCzG8G4OiDVgnaXeLMzj91bcQdYOMQ_82PTGrUbck3qSFXbug_Ljj8NZDT0J1ZSKv8Oce-GdkeNzA5W9yvChvorGotAUWMS7_EXXxz8mjlrwu6kyKfCpuJAMg5VrZaYA0nAlv-e7zoRE9pQ0VHNrEaj6Uikw3M02oVHUNiRtL5Y5tYyz_yRBauVLPdHf5Yf-cZeO2x02qFSGcl_2EzWZcGb6PkQZ_9QeOq_iJ9h-NU_wb9lnbebnBhPGAyc1-_9vnFlFzkH2lt0BVtfhW0E4ieKkntbC0QFxNu91Gf4jfFmsOAsCf3UpVqWIQw",215 "e":"AQAB"216 }217 """.trimIndent()218 val senderLookup = UseTestKey(junkPublicKeyStr) // Its the wrong trousers!219 // false means we failed to validate the sender's jwt.220 assertFalse(TokenAuthentication().checkSenderToken(senderToken, senderLookup, jtiCache))221 }222 @Test223 fun `test expired Sender key`() {224 val privateKey = jacksonObjectMapper().readValue(exampleRsaPrivateKeyStr, Jwk::class.java).toRSAPrivateKey()225 val senderToken = SenderUtils.generateSenderToken(226 sender,227 "http://baz.quux",228 privateKey,229 exampleKeyId,230 -65231 ) // expires in the past. Need to back past the clock skew232 val senderLookup = UseTestKey(exampleRsaPublicKeyStr) // Its the wrong trousers!233 // false means we failed to validate the sender's jwt.234 assertFalse(TokenAuthentication().checkSenderToken(senderToken, senderLookup, jtiCache))235 }236 @Test237 fun `test previously used Sender token`() {238 val privateKey = jacksonObjectMapper().readValue(exampleRsaPrivateKeyStr, Jwk::class.java).toRSAPrivateKey()239 val senderToken = SenderUtils.generateSenderToken(240 sender,241 "http://baz.quux",242 privateKey,243 exampleKeyId244 )245 val senderLookup = UseTestKey(exampleRsaPublicKeyStr) // Its the wrong trousers!246 // It should work the first time.247 assertTrue(TokenAuthentication().checkSenderToken(senderToken, senderLookup, jtiCache))248 // Then fail the second time249 assertFalse(TokenAuthentication().checkSenderToken(senderToken, senderLookup, jtiCache))250 }251 @Test252 fun `test MemoryJtiCache`() {253 val jtiCache = MemoryJtiCache()254 val uuid1 = UUID.randomUUID().toString()255 val exp1 = OffsetDateTime.now().plusSeconds(300)256 // First time it works257 assertTrue(jtiCache.isJTIOk(uuid1, exp1))258 // Second time it fails259 assertFalse(jtiCache.isJTIOk(uuid1, exp1))260 val uuid2 = UUID.randomUUID().toString()261 // Very short expiration -262 val exp2 = OffsetDateTime.now().plusSeconds(1)263 // First time it works264 assertTrue(jtiCache.isJTIOk(uuid2, exp2))265 Thread.sleep(2 * 1000)266 // Second time it fails, even if the original expired, due to the min timeout feature267 val exp2_1 = OffsetDateTime.now().plusSeconds(300)268 assertFalse(jtiCache.isJTIOk(uuid2, exp2_1))269 }270 @Test271 fun `test isExpiredToken`() {272 val exp1 = Date(System.currentTimeMillis() - 1)273 assertTrue(TokenAuthentication.isExpiredToken(exp1))274 val exp2 = Date(System.currentTimeMillis() + 1000)275 assertFalse(TokenAuthentication.isExpiredToken(exp2))276 }277 @Test278 fun `test checkAccessToken happy path`() {279 val rslookup = GetTestSecret() // callback to look up the Reportstream secret, using to sign RS token.280 val accessToken = tokenAuthentication.createAccessToken("myScope", rslookup)281 val claims = tokenAuthentication.checkAccessToken(accessToken.accessToken, "myScope", rslookup)282 // if claims is non-null then the sender's accessToken is valid.283 assertNotNull(claims)284 assertEquals(accessToken.expiresAtSeconds, claims["exp"])285 assertEquals("myScope", claims["scope"])286 }287 @Test288 fun `test empty scope to createAccessToken`() {289 val rslookup = GetTestSecret()290 assertFails { tokenAuthentication.createAccessToken("", rslookup) }291 assertFails { tokenAuthentication.createAccessToken(" ", rslookup) }292 }293 @Test294 fun `test checkAccessToken wrong reportstream secret`() {295 val rslookup1 = GetTestSecret()296 val accessToken = tokenAuthentication.createAccessToken("MyScope", rslookup1)297 val rslookup2 = GetTestSecret() // new/different secret298 val claims = tokenAuthentication.checkAccessToken(accessToken.accessToken, "MyScope", rslookup2)299 // if claims is non-null then the sender's accessToken is valid.300 assertNull(claims)301 }302 @Test303 fun `test scopeListContainsScope`() {304 assertTrue(Scope.scopeListContainsScope("a", "a"))305 assertTrue(Scope.scopeListContainsScope("a:b c:d e:f", "a:b"))306 assertFalse(Scope.scopeListContainsScope("a:b c:d e:f", "a:b "))307 assertFalse(Scope.scopeListContainsScope("", ""))308 assertFalse(Scope.scopeListContainsScope("xx", "x"))309 assertFalse(Scope.scopeListContainsScope("x x", ""))310 assertFalse(Scope.scopeListContainsScope("x x", " "))311 }312}...

Full Screen

Full Screen

BodyRepresentationTest.kt

Source:BodyRepresentationTest.kt Github

copy

Full Screen

1package com.github.kittinunf.fuel.core2import com.github.kittinunf.fuel.core.requests.DefaultBody3import com.github.kittinunf.fuel.test.MockHttpTestCase4import com.github.kittinunf.fuel.util.decodeBase645import org.hamcrest.CoreMatchers.equalTo6import org.hamcrest.MatcherAssert.assertThat7import org.junit.Test8import org.mockserver.model.BinaryBody9import java.io.ByteArrayInputStream10import java.net.URLConnection11import java.util.Random12class BodyRepresentationTest : MockHttpTestCase() {13 private val manager: FuelManager by lazy { FuelManager() }14 @Test15 fun emptyBodyRepresentation() {16 assertThat(17 DefaultBody.from({ ByteArrayInputStream(ByteArray(0)) }, { 0L }).asString("(unknown)"),18 equalTo("(empty)")19 )20 }21 @Test22 fun unknownBytesRepresentation() {23 val bytes = ByteArray(555 - 16)24 .also { Random().nextBytes(it) }25 .let { ByteArray(16).plus(it) }26 mock.chain(27 request = mock.request().withMethod(Method.GET.value).withPath("/bytes"),28 response = mock.response().withBody(BinaryBody(bytes, null)).withHeader("Content-Type", "")29 )30 val (_, response, _) = manager.request(Method.GET, mock.path("bytes")).responseString()31 assertThat(32 response.body().asString(response[Headers.CONTENT_TYPE].lastOrNull()),33 equalTo("(555 bytes of (unknown))")34 )35 }36 @Test37 fun guessContentType() {38 val decodedImage = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVQYV2NgYAAAAAMAAWgmWQ0AAAAASUVORK5CYII=".decodeBase64()!!39 assertThat(40 DefaultBody41 .from({ ByteArrayInputStream(decodedImage) }, { decodedImage.size.toLong() })42 .asString(URLConnection.guessContentTypeFromStream(ByteArrayInputStream(decodedImage))),43 equalTo("(${decodedImage.size} bytes of image/png)")44 )45 }46 @Test47 fun bytesRepresentationOfOctetStream() {48 val contentTypes = listOf("application/octet-stream")49 val content = ByteArray(555 - 16)50 .also { Random().nextBytes(it) }51 .let { ByteArray(16).plus(it) }52 contentTypes.forEach { contentType ->53 assertThat(54 DefaultBody55 .from({ ByteArrayInputStream(content) }, { content.size.toLong() })56 .asString(contentType),57 equalTo("(555 bytes of $contentType)")58 )59 }60 }61 @Test62 fun bytesRepresentationOfMedia() {63 val contentTypes = listOf(64 "image/bmp", "image/gif", "image/jpeg", "image/png", "image/tiff", "image/webp", "image/x-icon",65 "audio/aac", "audio/midi", "audio/x-midi", "audio/ogg", "audio/wav", "audio/webm", "audio/3gpp", "audio/3gpp2",66 "video/mpeg", "video/ogg", "video/webm", "video/x-msvideo", "video/3gpp", "video/3gpp2",67 "font/otf", "font/ttf", "font/woff", "font/woff2"68 )69 val content = ByteArray(555 - 16)70 .also { Random().nextBytes(it) }71 .let { ByteArray(16).plus(it) }72 contentTypes.forEach { contentType ->73 assertThat(74 DefaultBody75 .from({ ByteArrayInputStream(content) }, { content.size.toLong() })76 .asString(contentType),77 equalTo("(555 bytes of $contentType)")78 )79 }80 }81 @Test82 fun textRepresentationOfYaml() {83 val contentTypes = listOf("application/x-yaml", "text/yaml")84 val content = "language: c\n"85 contentTypes.forEach { contentType ->86 assertThat(87 DefaultBody88 .from({ ByteArrayInputStream(content.toByteArray()) }, { content.length.toLong() })89 .asString(contentType),90 equalTo(content)91 )92 }93 }94 @Test95 fun textRepresentationOfXml() {96 val contentTypes = listOf("application/xml", "application/xhtml+xml", "application/vnd.fuel.test+xml", "image/svg+xml")97 val content = "<html xmlns=\"http://www.w3.org/1999/xhtml\"/>"98 contentTypes.forEach { contentType ->99 assertThat(100 DefaultBody101 .from({ ByteArrayInputStream(content.toByteArray()) }, { content.length.toLong() })102 .asString(contentType),103 equalTo(content)104 )105 }106 }107 @Test108 fun textRepresentationOfScripts() {109 val contentTypes = listOf("application/javascript", "application/typescript", "application/vnd.coffeescript")110 val content = "function test()"111 contentTypes.forEach { contentType ->112 assertThat(113 DefaultBody114 .from({ ByteArrayInputStream(content.toByteArray()) }, { content.length.toLong() })115 .asString(contentType),116 equalTo(content)117 )118 }119 }120 @Test121 fun textRepresentationOfJson() {122 val contentTypes = listOf("application/json")123 val content = "{ \"foo\": 42 }"124 contentTypes.forEach { contentType ->125 assertThat(126 DefaultBody127 .from({ ByteArrayInputStream(content.toByteArray()) }, { content.length.toLong() })128 .asString(contentType),129 equalTo(content)130 )131 }132 }133 @Test134 fun textRepresentationOfJsonWithUtf8Charset() {135 val contentTypes = listOf("application/json;charset=utf-8", "application/json; charset=utf-8")136 val content = "{ \"foo\": 42 }"137 contentTypes.forEach { contentType ->138 assertThat(139 DefaultBody140 .from({ ByteArrayInputStream(content.toByteArray()) }, { content.length.toLong() })141 .asString(contentType),142 equalTo(content)143 )144 }145 }146 @Test147 fun textRepresentationOfJsonWithUtf8AndOtherParameters() {148 val contentTypes = listOf(149 "application/json;charset=utf-8;api-version=5.1",150 "application/json; charset=utf-8; api-version=5.1",151 "application/json;api-version=5.1;charset=utf-8",152 "application/json; api-version=5.1; charset=utf-8",153 "application/json;test=true;charset=utf-8;api-version=5.1",154 "application/json; test=true; charset=utf-8; api-version=5.1"155 )156 val content = "{ \"foo\": 42 }"157 contentTypes.forEach { contentType ->158 assertThat(159 DefaultBody160 .from({ ByteArrayInputStream(content.toByteArray()) }, { content.length.toLong() })161 .asString(contentType),162 equalTo(content)163 )164 }165 }166 @Test167 fun textRepresentationOfJsonWithDifferentCharsets() {168 val contentString = "{ \"foo\": 42 }"169 val contentMap = mapOf(170 "application/json; charset=utf-8" to Charsets.UTF_8,171 "application/json; charset=utf-16" to Charsets.UTF_16,172 "application/json; charset=utf-32" to Charsets.UTF_32,173 "application/json; charset=iso-8859-1" to Charsets.ISO_8859_1,174 "application/json; charset=ascii" to Charsets.US_ASCII175 )176 contentMap.forEach { (contentType, charset) ->177 assertThat(178 DefaultBody179 .from({ ByteArrayInputStream(contentString.toByteArray(charset)) }, { contentString.length.toLong() })180 .asString(contentType),181 equalTo(contentString)182 )183 }184 }185 @Test186 fun textRepresentationOfJsonWithoutCharset() {187 val contentTypes = listOf(188 "application/json;api-version=5.1",189 "application/json; api-version=5.1"190 )191 val content = "{ \"foo\": 42 }"192 contentTypes.forEach { contentType ->193 assertThat(194 DefaultBody195 .from({ ByteArrayInputStream(content.toByteArray()) }, { content.length.toLong() })196 .asString(contentType),197 equalTo(content)198 )199 }200 }201 @Test202 fun textRepresentationOfCsv() {203 val contentTypes = listOf("text/csv")204 val content = "function test()"205 contentTypes.forEach { contentType ->206 assertThat(207 DefaultBody208 .from({ ByteArrayInputStream(content.toByteArray()) }, { content.length.toLong() })209 .asString(contentType),210 equalTo(content)211 )212 }213 }214 @Test215 fun textRepresentationOfCsvWithUtf16beCharset() {216 val contentTypes = listOf("application/csv; charset=utf-16be", "application/csv;charset=utf-16be")217 val content = String("hello,world!".toByteArray(Charsets.UTF_16BE))218 contentTypes.forEach { contentType ->219 assertThat(220 DefaultBody221 .from({ ByteArrayInputStream(content.toByteArray()) }, { content.length.toLong() })222 .asString(contentType),223 equalTo("hello,world!")224 )225 }226 }227 @Test228 fun textRepresentationOfTextTypes() {229 val contentTypes = listOf("text/csv", "text/html", "text/calendar", "text/plain", "text/css")230 val content = "maybe invalid but we don't care"231 contentTypes.forEach { contentType ->232 assertThat(233 DefaultBody234 .from({ ByteArrayInputStream(content.toByteArray()) }, { content.length.toLong() })235 .asString(contentType),236 equalTo(content)237 )238 }239 }240}...

Full Screen

Full Screen

MockHelper.kt

Source:MockHelper.kt Github

copy

Full Screen

1package com.github.kittinunf.fuel.test2import com.github.kittinunf.fuel.core.Headers3import com.github.kittinunf.fuel.core.Parameters4import com.github.kittinunf.fuel.core.ResponseDeserializable5import com.github.kittinunf.fuel.util.decodeBase646import org.json.JSONArray7import org.json.JSONObject8import org.mockserver.integration.ClientAndServer9import org.mockserver.matchers.Times10import org.mockserver.model.HttpRequest11import org.mockserver.model.HttpResponse12import org.mockserver.model.HttpTemplate13import org.slf4j.event.Level14import java.net.URL15class MockHelper {16 private lateinit var mockServer: ClientAndServer17 fun setup(logLevel: Level = Level.WARN) {18 // This is not placed in a @BeforeClass / @BeforeAll so that the tests may have parallel19 // execution. When there is no port given as first argument, it will grab a free port20 this.mockServer = ClientAndServer.startClientAndServer()21 System.setProperty("mockserver.logLevel", logLevel.name)22 }23 fun tearDown() {24 mockServer.stop()25 }26 /**27 * The mock server for the current test run.28 *29 * Do not store this in a class variable as that will prohibit individual test cases from being30 * correctly parallelised without copying the class, and you can't / should not rely on31 * expected requests to be available across tests.32 *33 * @return [ClientAndServer]34 */35 fun server(): ClientAndServer = this.mockServer36 /**37 * Convenience method to request a request to its expected response38 *39 * @see request40 * @see response41 * @see reflect42 *43 * @example When you need different responses for the same request, you can reuse the request44 * with multiple calls to this method:45 *46 * val request = mock.request().withPath('/different-each-time')47 * mock.chain(request, mock.response().withStatusCode(500))48 * mock.chain(request, mock.response().withStatusCode(502))49 * mock.chain(request, mock.response().withStatusCode(204))50 *51 * // fetch('/different-each-time) => 50052 * // fetch('/different-each-time) => 50253 * // fetch('/different-each-time) => 20454 *55 * @param request [HttpRequest] the request56 * @param response [HttpResponse] the response57 * @param times [Times] times this can occur, defaults to once58 * @param server [ClientAndServer] the server to register on59 */60 fun chain(61 request: HttpRequest,62 response: HttpResponse,63 times: Times = Times.once(),64 server: ClientAndServer = server()65 ) {66 server.`when`(request, times).respond(response)67 }68 /**69 * @see chain(HttpRequest, HttpResponse, Times, ClientAndServer)70 */71 fun chain(72 request: HttpRequest,73 response: HttpTemplate,74 times: Times = Times.once(),75 server: ClientAndServer = server()76 ) {77 server.`when`(request, times).respond(response)78 }79 /**80 * Creates a new mock request.81 *82 * This method is introduced to keep the import out of test cases and to make it easy to replace83 * the library for mocking requests.84 *85 * @example mock request for posting on a path86 *87 * val request = mock.request().withMethod(Method.POST.value).withPath('/post-path')88 *89 * @return [HttpRequest]90 */91 fun request(): HttpRequest = HttpRequest.request()92 /**93 * Creates a new mock response.94 *95 * This method is introduced to keep the import out of test cases and to make it easy to replace96 * the library for mocking responses.97 */98 fun response(): HttpResponse = HttpResponse.response()99 /**100 * Creates a new mock response template.101 *102 * @see REFLECT_TEMPLATE103 * @see reflect104 *105 * This method is introduced to keep the import out of test cases and to make it easy to replace106 * the library for mocking requests.107 */108 fun responseTemplate(): HttpTemplate = HttpTemplate.template(HttpTemplate.TemplateType.JAVASCRIPT)109 /**110 * Creates a mock response that reflects what is coming in via the REFLECT_TEMPLATE template111 *112 * @see REFLECT_TEMPLATE113 *114 * This method is introduced to keep the import out of test cases and to make it easy to replace115 * the library for mocking requests.116 */117 fun reflect(): HttpTemplate = responseTemplate().withTemplate(REFLECT_TEMPLATE)118 /**119 * Generates the full path for a request to the given path120 *121 * @param path [String] the relative path122 * @return [String] the full path123 */124 fun path(path: String): String = URL("http://localhost:${server().localPort}/$path").toString()125 fun securedPath(path: String): String = URL("https://localhost:${server().localPort}/$path").toString()126 companion object {127 const val REFLECT_TEMPLATE = """128 return {129 'statusCode': 200,130 'headers': {131 'Date' : [ Date() ],132 'Content-Type' : [ 'application/json' ],133 'Cookie' : request.headers['cookie'] || []134 },135 'body': JSON.stringify(136 {137 method: request.method,138 path: request.path,139 query: request.queryStringParameters,140 body: request.body,141 headers: request.headers,142 reflect: true,143 userAgent: (request.headers['user-agent'] || request.headers['User-Agent'] || [])[0] }144 )145 };146 """147 }148}149data class MockReflected(150 val method: String,151 val path: String,152 val query: Parameters = listOf(),153 val body: MockReflectedBody? = null,154 val headers: Headers = Headers(),155 val reflect: Boolean = true,156 val userAgent: String? = null157) {158 operator fun get(key: String) = headers[key]159 class Deserializer : ResponseDeserializable<MockReflected> {160 override fun deserialize(content: String) = MockReflected.from(JSONObject(content))161 }162 companion object {163 fun from(json: JSONObject): MockReflected {164 val base = MockReflected(165 method = json.getString("method"),166 path = json.getString("path")167 )168 return json.keySet().fold(base) { current, key ->169 if (json.isNull(key)) {170 current171 } else {172 when (key) {173 "query" -> {174 val queryObject = json.getJSONObject(key)175 current.copy(176 query = queryObject.keySet().fold(listOf()) { query, parameter ->177 if (queryObject.isNull(parameter)) {178 query.plus(Pair(parameter, null))179 } else {180 val values = queryObject.get(parameter)181 when (values) {182 is JSONArray -> query.plus(Pair(parameter, values.toList()))183 else -> query.plus(Pair(parameter, values.toString()))184 }185 }186 }187 )188 }189 "body" -> current.copy(body = MockReflectedBody.from(190 json.optJSONObject(key) ?: JSONObject().put("type", "STRING").put("string", json.getString(key))191 ))192 "headers" -> current.copy(headers = Headers.from(json.getJSONObject(key).toMap()))193 "reflect" -> current.copy(reflect = json.getBoolean(key))194 "userAgent" -> current.copy(userAgent = json.getString("userAgent"))195 else -> current196 }197 }198 }199 }200 }201}202data class MockReflectedBody(203 val type: String,204 val string: String? = null,205 val binary: ByteArray? = null,206 val contentType: String? = null207) {208 companion object {209 fun from(json: JSONObject): MockReflectedBody {210 val base = MockReflectedBody(211 type = json.getString("type"),212 contentType = json.optString("contentType")213 )214 return when (base.type) {215 "STRING" -> base.copy(string = json.getString("string"))216 "BINARY" -> base.copy(binary = json.getString("binary").decodeBase64())217 else -> base218 }219 }220 }221 override fun equals(other: Any?): Boolean {222 if (this === other) return true223 if (javaClass != other?.javaClass) return false224 other as MockReflectedBody225 if (type != other.type) return false226 if (string != other.string) return false227 if (binary != null) {228 if (other.binary == null) return false229 if (!binary.contentEquals(other.binary)) return false230 } else if (other.binary != null) return false231 if (contentType != other.contentType) return false232 return true233 }234 override fun hashCode(): Int {235 var result = type.hashCode()236 result = 31 * result + (string?.hashCode() ?: 0)237 result = 31 * result + (binary?.contentHashCode() ?: 0)238 result = 31 * result + contentType.hashCode()239 return result240 }241}...

Full Screen

Full Screen

JwkTests.kt

Source:JwkTests.kt Github

copy

Full Screen

1package gov.cdc.prime.router.tokens2import com.fasterxml.jackson.databind.node.ArrayNode3import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper4import com.github.kittinunf.fuel.util.decodeBase645import com.nimbusds.jose.jwk.JWK6import com.nimbusds.jose.jwk.KeyType7import java.math.BigInteger8import kotlin.test.Test9import kotlin.test.assertEquals10import kotlin.test.assertNotNull11class JwkTests {12 val pemPublicESKey = """13-----BEGIN PUBLIC KEY-----14MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE0ks/RiTQ82tMW4UEQu0LLDqqEEcj6yce15ZF5YuUU+IqOKaMAu4/tsbyE+hM4WDjZYG6cSnYKoRhOoam4oHFernOLOkbJKzzC/165xzBqTIGx6SbmlcrPFPDjcJ8fn8CThVo17-----END PUBLIC KEY-----18 """.trimIndent()19 val affineX = "0ks_RiTQ82tMW4UEQu0LLDqqEEcj6yceZF5YuUU-IqOKaMAu4_tsbyE-hM4WDjZY"20 val affineY = "G6cSnYKoRhOoam4oHFernOLOkbJKzzC_5xzBqTIGx6SbmlcrPFPDjcJ8fn8CThVo"21 val ecPublicKeyStr = """22 {23 "kid": "1234",24 "kty":"EC",25 "crv":"P-384",26 "x":"$affineX",27 "y":"$affineY"28 }29 """.trimIndent()30 val ecPrivateKey = """31 {32 "kid": "1234",33 "kty":"EC",34 "d":"ty7q_3nZCTaY80-69YHJ18cN2vC1lRIuULMeKvhpg6C24fxCw_vHjHlF80EzcTX7",35 "crv":"P-384",36 "x":"$affineX",37 "y":"$affineY"38 }39 """.trimIndent()40 val modulus = "xJRuufBk_axjyO1Kpy5uwmnAY0VUhCzG8G4OiDVgnaXeLMzj91bcQdYOMQ_82PTGrUbck3qSFXbug_Ljj8NZDT0J1ZSKv8Oce-" +41 "GdkeNzA5W9yvChvorGotAUWMS7_EXXxz8mjlrwu6kyKfCpuJAMg5VrZaYA0nAlv-e7zoRE9pQ0VHNrEaj6Uikw3M02oVHUNiRtL5Y5tYyz_y" +42 "RBauVLPdHf5Yf-cZeO2x02qFSGcl_2EzWZcGb6PkQZ_9QeOq_iJ9h-NU_wb9lnbebnBhPGAyc1-_9vnFlFzkH2lt0BVtfhW0E4ieKkntbC0Q" +43 "FxNu91Gf4jfFmsOAsCf3UpVqWIQw"44 val exponent = "AQAB"45 val rsaPublicKeyStr = """46 {47 "kty":"RSA",48 "kid":"11209921-860e-4b6d-8d7e-adc8778e1c6c",49 "n": "$modulus",50 "e": "$exponent"51 }52 """.trimIndent()53 val jwkString = """54 { "kty": "ES",55 "use": "sig",56 "x5c": [ "a", "b", "c" ]57 }58 """.trimIndent()59 val jwk = Jwk(kty = "ES", x = "x", y = "y", crv = "crv", kid = "myId", x5c = listOf("a", "b"))60 // this jwkset is from the RFC specification for JWKs, so I thought it would be a nice test.61 // See https://tools.ietf.org/html/rfc751762 val niceExampleJwkSetString = """63 { 64 "scope": "foobar",65 "keys":66 [67 {"kty":"EC",68 "crv":"P-256",69 "x":"MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4",70 "y":"4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM",71 "use":"enc",72 "kid":"1"},73 {"kty":"RSA",74 "n": "0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw", "e":"AQAB",75 "alg":"RS256",76 "kid":"2011-04-29"}77 ]78 }79 """.trimIndent()80 @Test81 fun `test convert json string to Jwk obj`() {82 val obj: Jwk = jacksonObjectMapper().readValue(jwkString, Jwk::class.java)83 assertNotNull(obj)84 assertEquals("ES", obj.kty)85 assertEquals(3, obj.x5c?.size)86 assertEquals("c", obj.x5c?.get(2))87 }88 @Test89 fun `test covert Jwk obj to json string`() {90 val json = jacksonObjectMapper().writeValueAsString(jwk)91 assertNotNull(json)92 val tree = jacksonObjectMapper().readTree(json)93 assertEquals("ES", tree["kty"].textValue())94 assertEquals("x", tree["x"].textValue())95 assertEquals("b", (tree["x5c"] as ArrayNode)[1].textValue())96 }97 @Test98 fun `test convert JSON String to RSAPublicKey`() {99 val rsaPublicKey = Jwk.generateRSAPublicKey(rsaPublicKeyStr)100 assertNotNull(rsaPublicKey)101 assertEquals("RSA", rsaPublicKey.algorithm)102 assertNotNull(rsaPublicKey) // lame test103 assertEquals(BigInteger(exponent.decodeBase64()), rsaPublicKey.publicExponent)104 // not so straightforward as this105 // assertEquals(BigInteger(modulus.decodeBase64()), rsaPublicKey.modulus)106 }107 @Test108 fun `test convert JSON String to ECPublicKey`() {109 val ecPublicKey = Jwk.generateECPublicKey(ecPublicKeyStr)110 assertNotNull(ecPublicKey)111 assertNotNull(ecPublicKey)112 assertEquals("EC", ecPublicKey.algorithm)113 assertNotNull(ecPublicKey.w) // lame test114 // not so straightforward as this115 // assertEquals(BigInteger(affineX.decodeBase64()), ecPublicKey.w.affineX)116 }117 @Test118 fun `test convert pem to ECPublicKey`() {119 // Step 1: convert the .pem file into a nimbusds JWK obj.120 val nimbusdsJwk = JWK.parseFromPEMEncodedObjects(pemPublicESKey)121 assertEquals(KeyType.EC, nimbusdsJwk.keyType)122 // Steps 2,3: convert the JWK obj to a string, then use that to generate the public key obj123 val ecPublicKey = Jwk.generateECPublicKey(nimbusdsJwk.toJSONString())124 assertNotNull(ecPublicKey)125 assertEquals("EC", ecPublicKey.algorithm)126 assertNotNull(ecPublicKey.w) // lame test127 }128 @Test129 fun `test converting nice example JwkSet string to obj`() {130 val jwkSet = jacksonObjectMapper().readValue(niceExampleJwkSetString, JwkSet::class.java)131 assertEquals("foobar", jwkSet.scope)132 assertEquals(2, jwkSet.keys.size)133 val key1 = jwkSet.keys[0]134 assertEquals("EC", key1.kty)135 assertEquals("enc", key1.use)136 assertEquals("1", key1.kid)137 val key2 = jwkSet.keys[1]138 assertEquals("RSA", key2.kty)139 assertEquals("RS256", key2.alg)140 assertEquals("2011-04-29", key2.kid)141 }142 @Test143 fun `test converting nice example JwkSet string to RSA and EC public keys`() {144 val jwkSet = jacksonObjectMapper().readValue(niceExampleJwkSetString, JwkSet::class.java)145 assertEquals("foobar", jwkSet.scope)146 assertEquals(2, jwkSet.keys.size)147 val ecPublicKey = jwkSet.keys[0].toECPublicKey()148 assertNotNull(ecPublicKey)149 assertEquals("EC", ecPublicKey.algorithm)150 assertNotNull(ecPublicKey.w) // lame test151 val rsaPublicKey = jwkSet.keys[1].toRSAPublicKey()152 assertNotNull(rsaPublicKey)153 assertEquals("RSA", rsaPublicKey.algorithm)154 assertNotNull(rsaPublicKey) // lame test155 assertEquals(BigInteger(exponent.decodeBase64()), rsaPublicKey.publicExponent)156 }157 @Test158 fun `test convert string FHIRAuth to ECPublicKey`() {159 val jwkSetString = """160 { 161 "scope": "read:reports",162 "keys": [ $ecPublicKeyStr ]163 }164 """.trimIndent()165 val jwkSet = jacksonObjectMapper().readValue(jwkSetString, JwkSet::class.java)166 val ecPublicKey = jwkSet.keys[0].toECPublicKey()167 assertNotNull(ecPublicKey)168 assertEquals("EC", ecPublicKey.algorithm)169 assertNotNull(ecPublicKey.w) // lame test170 }171}...

Full Screen

Full Screen

Base64.kt

Source:Base64.kt Github

copy

Full Screen

1package com.github.kittinunf.fuel.util2/**3 * Inspired From https://github.com/square/okio/blob/master/okio/src/main/kotlin/okio/-Base64.kt4 */5import java.lang.System.arraycopy6fun ByteArray.encodeBase64(): ByteArray = encodeBase64ToArray()7fun ByteArray.encodeBase64Url(): ByteArray = encodeBase64ToArray(map = BASE64_URL_SAFE)8fun String.encodeBase64ToString(): String = String(toByteArray().encodeBase64())9fun String.encodeBase64UrlToString(): String = String(toByteArray().encodeBase64Url())10fun String.decodeBase64(): ByteArray? = decodeBase64ToArray()?.let { it }11fun String.decodeBase64ToString(): String? = decodeBase64ToArray()?.let { String(it) }12private val regular = listOf(('A'..'Z'), ('a'..'z'), ('0'..'9'), listOf('+', '/'))13private val urlSafe = listOf(('A'..'Z'), ('a'..'z'), ('0'..'9'), listOf('-', '_'))14private val BASE64 = regular.flatten().map { it.toByte() }.toByteArray()15private val BASE64_URL_SAFE = urlSafe.flatten().map { it.toByte() }.toByteArray()16private fun ByteArray.encodeBase64ToArray(map: ByteArray = BASE64): ByteArray {17 val length = (size + 2) / 3 * 418 val out = ByteArray(length)19 var index = 020 val end = size - size % 321 var i = 022 while (i < end) {23 val b0 = this[i++].toInt()24 val b1 = this[i++].toInt()25 val b2 = this[i++].toInt()26 out[index++] = map[(b0 and 0xff shr 2)]27 out[index++] = map[(b0 and 0x03 shl 4) or (b1 and 0xff shr 4)]28 out[index++] = map[(b1 and 0x0f shl 2) or (b2 and 0xff shr 6)]29 out[index++] = map[(b2 and 0x3f)]30 }31 when (size - end) {32 1 -> {33 val b0 = this[i].toInt()34 out[index++] = map[b0 and 0xff shr 2]35 out[index++] = map[b0 and 0x03 shl 4]36 out[index++] = '='.toByte()37 out[index] = '='.toByte()38 }39 2 -> {40 val b0 = this[i++].toInt()41 val b1 = this[i].toInt()42 out[index++] = map[(b0 and 0xff shr 2)]43 out[index++] = map[(b0 and 0x03 shl 4) or (b1 and 0xff shr 4)]44 out[index++] = map[(b1 and 0x0f shl 2)]45 out[index] = '='.toByte()46 }47 }48 return out49}50private fun String.decodeBase64ToArray(): ByteArray? {51 // Ignore trailing '=' padding and whitespace from the input.52 var limit = length53 while (limit > 0) {54 val c = this[limit - 1]55 if (c != '=' && c != '\n' && c != '\r' && c != ' ' && c != '\t') {56 break57 }58 limit--59 }60 // If the input includes whitespace, this output array will be longer than necessary.61 val out = ByteArray((limit * 6L / 8L).toInt())62 var outCount = 063 var inCount = 064 var word = 065 for (pos in 0 until limit) {66 val c = this[pos]67 val bits: Int68 if (c in 'A'..'Z') {69 // char ASCII value70 // A 65 071 // Z 90 25 (ASCII - 65)72 bits = c.toInt() - 6573 } else if (c in 'a'..'z') {74 // char ASCII value75 // a 97 2676 // z 122 51 (ASCII - 71)77 bits = c.toInt() - 7178 } else if (c in '0'..'9') {79 // char ASCII value80 // 0 48 5281 // 9 57 61 (ASCII + 4)82 bits = c.toInt() + 483 } else if (c == '+' || c == '-') {84 bits = 6285 } else if (c == '/' || c == '_') {86 bits = 6387 } else if (c == '\n' || c == '\r' || c == ' ' || c == '\t') {88 continue89 } else {90 return null91 }92 // Append this char's 6 bits to the word.93 word = word shl 6 or bits94 // For every 4 chars of input, we accumulate 24 bits of output. Emit 3 bytes.95 inCount++96 if (inCount % 4 == 0) {97 out[outCount++] = (word shr 16).toByte()98 out[outCount++] = (word shr 8).toByte()99 out[outCount++] = word.toByte()100 }101 }102 val lastWordChars = inCount % 4103 when (lastWordChars) {104 1 -> {105 // We read 1 char followed by "===". But 6 bits is a truncated byte! Fail.106 return null107 }108 2 -> {109 // We read 2 chars followed by "==". Emit 1 byte with 8 of those 12 bits.110 word = word shl 12111 out[outCount++] = (word shr 16).toByte()112 }113 3 -> {114 // We read 3 chars, followed by "=". Emit 2 bytes for 16 of those 18 bits.115 word = word shl 6116 out[outCount++] = (word shr 16).toByte()117 out[outCount++] = (word shr 8).toByte()118 }119 }120 // If we sized our out array perfectly, we're done.121 if (outCount == out.size) return out122 // Copy the decoded bytes to a new, right-sized array.123 val prefix = ByteArray(outCount)124 arraycopy(out, 0, prefix, 0, outCount)125 return prefix126}...

Full Screen

Full Screen

Base64Test.kt

Source:Base64Test.kt Github

copy

Full Screen

1/**2 * Copied From https://github.com/square/okio/blob/master/okio/src/test/kotlin/okio/ByteStringTest.kt3 */4package com.github.kittinunf.fuel.util5import org.junit.Assert.assertArrayEquals6import org.junit.Assert.assertEquals7import org.junit.Test8class Base64Test {9 @Test10 fun encodeBase64() {11 assertEquals("", "".encodeBase64ToString())12 assertEquals("AA==", "\u0000".encodeBase64ToString())13 assertEquals("AAA=", "\u0000\u0000".encodeBase64ToString())14 assertEquals("AAAA", "\u0000\u0000\u0000".encodeBase64ToString())15 assertEquals("SG93IG1hbnkgbGluZXMgb2YgY29kZSBhcmUgdGhlcmU/ICdib3V0IDIgbWlsbGlvbi4=",16 "How many lines of code are there? 'bout 2 million.".encodeBase64ToString())17 }18 @Test19 fun encodeBase64Url() {20 assertEquals("", "".encodeBase64UrlToString())21 assertEquals("AA==", "\u0000".encodeBase64UrlToString())22 assertEquals("AAA=", "\u0000\u0000".encodeBase64UrlToString())23 assertEquals("AAAA", "\u0000\u0000\u0000".encodeBase64UrlToString())24 assertEquals("SG93IG1hbnkgbGluZXMgb2YgY29kZSBhcmUgdGhlcmU_ICdib3V0IDIgbWlsbGlvbi4=",25 "How many lines of code are there? 'bout 2 million.".encodeBase64UrlToString())26 }27 @Test28 fun ignoreUnnecessaryPadding() {29 assertEquals(null, "\\fgfgff\\".decodeBase64ToString())30 assertEquals("", "====".decodeBase64ToString())31 assertEquals("\u0000\u0000\u0000", "AAAA====".decodeBase64ToString())32 }33 @Test34 fun decodeBase64() {35 assertArrayEquals("".toByteArray(), "".decodeBase64())36 assertEquals("", "".decodeBase64ToString())37 assertEquals(null, "/===".decodeBase64ToString()) // Can't do anything with 6 bits!38 assertEquals("What's to be scared about? It's just a little hiccup in the power...",39 ("V2hhdCdzIHRvIGJlIHNjYXJlZCBhYm91dD8gSXQncyBqdXN0IGEgbGl0dGxlIGhpY2" +40 "N1cCBpbiB0aGUgcG93ZXIuLi4=").decodeBase64ToString())41 assertEquals("How many lines of code are there>", "SG93IG1hbnkgbGluZXMgb2YgY29kZSBhcmUgdGhlcmU+".decodeBase64ToString())42 }43 @Test44 fun decodeBase64WithWhitespace() {45 assertEquals("\u0000\u0000\u0000", " AA AA ".decodeBase64ToString())46 assertEquals("\u0000\u0000\u0000", " AA A\r\nA ".decodeBase64ToString())47 assertEquals("\u0000\u0000\u0000", "AA AA".decodeBase64ToString())48 assertEquals("\u0000\u0000\u0000", " AA AA ".decodeBase64ToString())49 assertEquals("\u0000\u0000\u0000", " AA A\r\nA ".decodeBase64ToString())50 assertEquals("\u0000\u0000\u0000", "A AAA".decodeBase64ToString())51 assertEquals("", " ".decodeBase64ToString())52 }53}...

Full Screen

Full Screen

Totp.kt

Source:Totp.kt Github

copy

Full Screen

1package me.sunrisem.steamweb2import com.beust.klaxon.Klaxon3import com.github.kittinunf.fuel.httpPost4import org.apache.commons.codec.binary.Base645import java.nio.ByteBuffer6import java.nio.ByteOrder7import java.util.*8import javax.crypto.Mac9import javax.crypto.spec.SecretKeySpec10import kotlin.experimental.and11class SteamTotp {12 private fun getCurrentTime(_timeOffset: Long?): Long {13 var timeOffset: Long = 014 if (_timeOffset != null) timeOffset = _timeOffset15 return (System.currentTimeMillis() / 1000L) + timeOffset16 }17 fun getTimeDiff(): Long {18 class TimeData(val server_time: String)19 class QueryTime(val response: TimeData)20 val url = "http://api.steampowered.com/ITwoFactorService/QueryTime/v1/"21 val (request, response, result) = url.httpPost().responseString()22 val json = Klaxon().parse<QueryTime>(result.get())23 if (json == null) throw Error("Couldn't parse JSON")24 val resServerTime = json.response.server_time.toInt()25 return resServerTime - getCurrentTime(null)26 }27 fun getAuthCode(sharedSecret: String, _timeOffset: Long?): String {28 var timeOffset = _timeOffset29 if (_timeOffset == null) timeOffset = getTimeDiff()30 val unixTime = getCurrentTime(timeOffset)31 val keyBytes = Base64.decodeBase64(sharedSecret)32 val signingKey = SecretKeySpec(keyBytes, "HmacSHA1")33 val mac = Mac.getInstance("HmacSHA1")34 mac.init(signingKey)35 val time = (unixTime / 30).toInt()36 val b = ByteBuffer.allocate(8)37 b.putInt(4, time)38 b.order(ByteOrder.BIG_ENDIAN)39 val result2 = b.array()40 val rawHmac = mac.doFinal(result2)41 val start = (rawHmac[19] and 0x0F).toByte()42 var bytes: ByteArray43 bytes = Arrays.copyOfRange(rawHmac, start.toInt(), start + 4)44 val wrapped = ByteBuffer.wrap(bytes)45 val codeInt = wrapped.int46 var fullcode = codeInt and 0x7fffffff and -0x147 val chars = "23456789BCDFGHJKMNPQRTVWXY"48 var code = ""49 for (i in 0..4) {50 val curChar = chars[fullcode % chars.length].toString()51 code += curChar52 fullcode /= chars.length53 }54 return code55 }56}...

Full Screen

Full Screen

String.decodeBase64

Using AI Code Generation

copy

Full Screen

1val base64String = String.decodeBase64(base64String)2val base64String = String.encodeBase64(base64String)3val base64String = String.decodeBase64(base64String)4val base64String = String.encodeBase64(base64String)5val base64String = String.decodeBase64(base64String)6val base64String = String.encodeBase64(base64String)7val base64String = String.decodeBase64(base64String)8val base64String = String.encodeBase64(base64String)9val base64String = String.decodeBase64(base64String)10val base64String = String.encodeBase64(base64String)11val base64String = String.decodeBase64(base64String)12val base64String = String.encodeBase64(base64String)13val base64String = String.decodeBase64(base64String)14val base64String = String.encodeBase64(base64String)

Full Screen

Full Screen

String.decodeBase64

Using AI Code Generation

copy

Full Screen

1val decodedString = Base64.decodeBase64(base64String)2println(decodedString)3val encodedString = Base64.encodeBase64(base64String)4println(encodedString)5val decodedString = Base64.decodeBase64(base64String)6println(decodedString)7val encodedString = Base64.encodeBase64(base64String)8println(encodedString)9val decodedString = Base64.decodeBase64(base64String)10println(decodedString)11val encodedString = Base64.encodeBase64(base64String)12println(encodedString)13val decodedString = Base64.decodeBase64(base64String)14println(decodedString)15val encodedString = Base64.encodeBase64(base64String)16println(encodedString)17val decodedString = Base64.decodeBase64(base64String)18println(decodedString)

Full Screen

Full Screen

String.decodeBase64

Using AI Code Generation

copy

Full Screen

1byte[] decodedBytes = Base64.decodeBase64(base64String);2byte[] decodedBytes = Base64.getDecoder().decode(base64String);3byte[] decodedBytes = Base64.decodeBase64(base64String);4byte[] decodedBytes = DatatypeConverter.parseBase64Binary(base64String);5byte[] decodedBytes = Base64.getUrlDecoder().decode(base64String);6byte[] decodedBytes = Base64.getMimeDecoder().decode(base64String);7byte[] decodedBytes = Base64.decode(base64String);8byte[] decodedBytes = Base64.decodeBase64(base64String);9byte[] decodedBytes = Base64.decodeBase64(base64String);10byte[] decodedBytes = Base64.decodeBase64(base64String);11byte[] decodedBytes = Base64.decodeBase64(base64String);12byte[] decodedBytes = Base64.decodeBase64(base64String);13byte[] decodedBytes = Base64.decodeBase64(base64String);

Full Screen

Full Screen

String.decodeBase64

Using AI Code Generation

copy

Full Screen

1 val decodedBase64 = String(Base64.decodeBase64(base64String))2 println(decodedBase64)3 val decodedBase64 = String(Base64.decodeBase64(base64String))4 println(decodedBase64)5 val decodedBase64 = String(Base64.decodeBase64(base64String))6 println(decodedBase64)7 val decodedBase64 = String(Base64.decodeBase64(base64String))8 println(decodedBase64)9 val decodedBase64 = String(Base64.decodeBase64(base64String))10 println(decodedBase64)11 val decodedBase64 = String(Base64.decodeBase64(base64String))12 println(decodedBase64)13 val decodedBase64 = String(Base64.decodeBase64(base64String))14 println(decodedBase64)15 val decodedBase64 = String(Base64.decodeBase64(base64String))16 println(decodedBase64)17 val decodedBase64 = String(Base64.decodeBase64(base64String))18 println(decodedBase64)

Full Screen

Full Screen

String.decodeBase64

Using AI Code Generation

copy

Full Screen

1val base64 = Base64()2val decodedString = base64.decodeBase64(“SGVsbG8gV29ybGQh”)3println(decodedString)4val base64 = Base64()5val encodedString = base64.encodeBase64(“Hello World!”)6println(encodedString)7val decodedString = “SGVsbG8gV29ybGQh”.decodeBase64()8println(decodedString)9val encodedString = “Hello World!”.encodeBase64()10println(encodedString)

Full Screen

Full Screen

String.decodeBase64

Using AI Code Generation

copy

Full Screen

1import com.github.kittinunf.fuel.Fuel2import com.github.kittinunf.fuel.core.FuelManager3import com.github.kittinunf.fuel.core.Method4import com.github.kittinunf.fuel.core.Request5import com.github.kittinunf.fuel.core.Response6import com.github.kittinunf.fuel.core.requests.DefaultBody7import com.github.kittinunf.fuel.core.requests.DefaultRequest8import com.github.kittinunf.fuel.core.requests.cUrlRequest9import com.github.kittinunf.fuel.core.requests.downloadRequest10import com.github.kittinunf.fuel.core.requests.request11import com.github.kittinunf.fuel.core.requests.streamRequest12import com.github.kittinunf.fuel.core.requests.uploadRequest13import com.github.kittinunf.fuel.core.requests.urlEncodedBody14import com.github.kittinunf.fuel.json.responseJson15import com.github.kittinunf.fuel.util.Base6416import com.github.kittinunf.result.Result17import java.io.File18import java.io.InputStream19import java.net.URL20import java.nio.charset.Charset21object FuelExample {22 fun main(args: Array<String>) {23 println(request)24 println(response)25 println(result)26 println(request1)27 println(response1)28 println(result1)29 println(request2)30 println(response2)31 println(result2)32 println(request

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful