java.util.Base64 Java Examples

The following examples show how to use java.util.Base64. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ImageLayout.java    From Alice-LiveMan with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void paintLayout(Graphics2D g) throws IOException {
    if (imageBase64 == null) {
        int startPoint = src.indexOf(",");
        if (startPoint > -1) {
            imageBase64 = src.substring(startPoint + 1);
        } else {
            imageBase64 = src;
        }
    }
    byte[] bytes = Base64.getDecoder().decode(imageBase64);
    try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes)) {
        BufferedImage image = ImageIO.read(bis);
        Composite oldComp = g.getComposite();
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, opacity));
        g.drawImage(image.getScaledInstance(width, height, Image.SCALE_SMOOTH), x, y, null);
        g.setComposite(oldComp);
    }
}
 
Example #2
Source File: Base64GetEncoderTest.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
private static void testWrapEncode2(final Base64.Encoder encoder)
        throws IOException {
    System.err.println("\nEncoder.wrap test II ");
    final byte[] secondTestBuffer =
            "api/java_util/Base64/index.html#GetEncoderMimeCustom[noLineSeparatorInEncodedString]"
            .getBytes(US_ASCII);
    String base64EncodedString;
    ByteArrayOutputStream secondEncodingStream = new ByteArrayOutputStream();
    OutputStream base64EncodingStream = encoder.wrap(secondEncodingStream);
    base64EncodingStream.write(secondTestBuffer);
    base64EncodingStream.close();

    final byte[] encodedByteArray = secondEncodingStream.toByteArray();

    System.err.print("result = " + new String(encodedByteArray, US_ASCII)
            + "  after wrap Base64 encoding of string");

    base64EncodedString = new String(encodedByteArray, US_ASCII);

    if (base64EncodedString.contains("$$$")) {
        throw new RuntimeException(
                "Base64 encoding contains line separator after wrap 2 invoked  ... \n");
    }
}
 
Example #3
Source File: OTATest.java    From blynk-server with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testOTAWrongToken() throws Exception {
    HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start?token=" + 123);
    post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth));

    String fileName = "test.bin";

    InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName);
    ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("upfile", fileBody);
    HttpEntity entity = builder.build();

    post.setEntity(entity);

    try (CloseableHttpResponse response = httpclient.execute(post)) {
        assertEquals(400, response.getStatusLine().getStatusCode());
        String error = TestUtil.consumeText(response);

        assertNotNull(error);
        assertEquals("Invalid token.", error);
    }
}
 
Example #4
Source File: JwtUtil.java    From cubeai with Apache License 2.0 6 votes vote down vote up
public static String getUserLogin(HttpServletRequest httpServletRequest) {
    String authorization = httpServletRequest.getHeader("authorization");
    if (null == authorization) {
        // 请求头中没有携带JWT,表示非登录用户
        return null;
    }

    String jwt = authorization.substring(7); // 去除前缀“bearer ”
    String payloadBase64 = jwt.substring(jwt.indexOf(".") + 1, jwt.lastIndexOf(".")); // 取出JWT中第二部分
    Base64.Decoder decoder = Base64.getDecoder();
    String payloadString;
    try {
        payloadString = new String(decoder.decode(payloadBase64), "UTF-8");
    } catch (Exception e) {
        return null;
    }
    JSONObject payloadJson = JSONObject.parseObject(payloadString);

    String userLogin = payloadJson.getString("user_name");
    if (null == userLogin) {
        return "system"; // 如果JWT中没有携带用户名,则应该是微服务见内部调用,此时将用户名强制设为system返回。
    } else {
        return userLogin;
    }
}
 
Example #5
Source File: MicroGatewayCommonUtil.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Get the tenant username password mapping from the enabled tenants
 *
 * @return Map<tenantUsername, Password> for all the tenants
 * @throws OnPremiseGatewayException if failed to retrieve the users
 */
public static Map<String, String> getMultiTenantUserMap() throws OnPremiseGatewayException {

    ArrayList multiTenantUsers = ConfigManager.getConfigurationDTO().getMulti_tenant_users();
    if (!multiTenantUsers.isEmpty()) {
        Map<String, String> tenantUserPasswordMap = new HashMap<>();
        for (Object tenantUserCredential : multiTenantUsers) {
            byte[] decodedUser = Base64.getDecoder().decode(tenantUserCredential.toString());
            String decodedUserString = new String(decodedUser);
            String[] userDetails = decodedUserString.split(":");
            tenantUserPasswordMap.put(userDetails[0], userDetails[1]);
        }
        return tenantUserPasswordMap;
    } else {
        throw new OnPremiseGatewayException("Multi Tenant User list is not defined in the on-premise-gateway.toml" +
                " file");
    }
}
 
Example #6
Source File: HwYunMsgSender.java    From WePush with MIT License 6 votes vote down vote up
/**
 * 构造X-WSSE参数值
 *
 * @param appKey
 * @param appSecret
 * @return
 */
static String buildWsseHeader(String appKey, String appSecret) {
    if (null == appKey || null == appSecret || appKey.isEmpty() || appSecret.isEmpty()) {
        System.out.println("buildWsseHeader(): appKey or appSecret is null.");
        return null;
    }
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    String time = sdf.format(new Date()); //Created
    String nonce = UUID.randomUUID().toString().replace("-", ""); //Nonce

    byte[] passwordDigest = DigestUtils.sha256(nonce + time + appSecret);
    String hexDigest = Hex.encodeHexString(passwordDigest);

    //如果JDK版本是1.8,请加载原生Base64类,并使用如下代码
    String passwordDigestBase64Str = Base64.getEncoder().encodeToString(hexDigest.getBytes()); //PasswordDigest
    //如果JDK版本低于1.8,请加载三方库提供Base64类,并使用如下代码
    //String passwordDigestBase64Str = Base64.encodeBase64String(hexDigest.getBytes(Charset.forName("utf-8"))); //PasswordDigest
    //若passwordDigestBase64Str中包含换行符,请执行如下代码进行修正
    //passwordDigestBase64Str = passwordDigestBase64Str.replaceAll("[\\s*\t\n\r]", "");

    return String.format(WSSE_HEADER_FORMAT, appKey, passwordDigestBase64Str, nonce, time);
}
 
Example #7
Source File: TalkClient.java    From Talk with MIT License 6 votes vote down vote up
private void sendMsg() {
	String curUsr = getUsrName(usrsListView.getSelectionModel().getSelectedItem());
	if(sendMsg.getText() != null && ! Pattern.matches("\\n*", sendMsg.getText())) {
		out.printf("[SENDTO %s]%s\n", curUsr, Base64.getEncoder().encodeToString(sendMsg.getText().getBytes(StandardCharsets.UTF_8)));
		out.flush();
		String Msg = String.format("[%s <%s>] %s\n",
				new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()),
				usrName, sendMsg.getText()
				);
		if(usrsMsg.get(curUsr) != null)
			usrsMsg.put(curUsr, usrsMsg.get(curUsr) + Msg);
		else
			usrsMsg.put(curUsr, Msg);
		message.appendText(Msg);
		sendMsg.setText("");
	} else {
		sendMsg.setText("");
	}
}
 
Example #8
Source File: SensitiveDataCryptoUtilsTest.java    From chvote-1-0 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * saving a key and retrieving it from a file should give the same object
 */
@Test
public void saveAndRetrieveSecretKey() throws IOException, ClassNotFoundException {
    SecretKey sK = SensitiveDataCryptoUtils.buildSecretKey(SECRETKEY_LENGTH, configuration.getPbkdf2Algorithm());
    String secretKeyFingerPrint = Base64.getEncoder().encodeToString(sK.getEncoded());

    File keyFile = File.createTempFile("keyfile", "key");
    keyFile.deleteOnExit();

    saveInFile(keyFile, sK);

    ObjectInputStream ois = new ObjectInputStream(new FileInputStream(keyFile));
    SecretKey readKey = (SecretKey) ois.readObject();
    ois.close();

    assertTrue(readKey.getEncoded().length * 8 == SECRETKEY_LENGTH);
    assertTrue(Base64.getEncoder().encodeToString(readKey.getEncoded()).equals(secretKeyFingerPrint));
}
 
Example #9
Source File: SecretUtils.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
public static void waitForCertToChange(String originalCert, String secretName) {
    LOGGER.info("Waiting for Secret {} certificate change", secretName);
    TestUtils.waitFor("Cert to be replaced", Constants.GLOBAL_POLL_INTERVAL, Constants.TIMEOUT_FOR_CLUSTER_STABLE, () -> {
        Secret secret = kubeClient().getSecret(secretName);
        if (secret != null && secret.getData() != null && secret.getData().containsKey("ca.crt")) {
            String currentCert = new String(Base64.getDecoder().decode(secret.getData().get("ca.crt")), StandardCharsets.US_ASCII);
            boolean changed = !originalCert.equals(currentCert);
            if (changed) {
                LOGGER.info("Certificate in Secret {} has changed, was {}, is now {}", secretName, originalCert, currentCert);
            }
            return changed;
        } else {
            return false;
        }
    });
}
 
Example #10
Source File: EncryptKitTest.java    From blade with Apache License 2.0 6 votes vote down vote up
@Test
public void encrypt3DES() throws Exception {
    assertTrue(
            Arrays.equals(
                    bytesResDES3,
                    EncryptKit.encrypt3DES(bytesDataDES3, bytesKeyDES3)
            )
    );
    assertEquals(
            res3DES,
            EncryptKit.encrypt3DES2HexString(bytesDataDES3, bytesKeyDES3)
    );
    assertTrue(
            Arrays.equals(
                    Base64.getEncoder().encode(bytesResDES3),
                    EncryptKit.encrypt3DES2Base64(bytesDataDES3, bytesKeyDES3)
            )
    );
}
 
Example #11
Source File: EmbeddedAssetCreatorV2.java    From JglTF with MIT License 6 votes vote down vote up
/**
 * Convert the given {@link Buffer} into an embedded buffer, by replacing 
 * its URI with a data URI, if the URI is not already a data URI
 * 
 * @param gltfModel The {@link GltfModelV2}
 * @param index The index of the {@link Buffer}
 * @param buffer The {@link Buffer}
 */
private static void convertBufferToEmbedded(
    GltfModelV2 gltfModel, int index, Buffer buffer)
{
    String uriString = buffer.getUri();
    if (IO.isDataUriString(uriString))
    {
        return;
    }
    BufferModel bufferModel = gltfModel.getBufferModels().get(index);
    ByteBuffer bufferData = bufferModel.getBufferData();
    
    byte data[] = new byte[bufferData.capacity()];
    bufferData.slice().get(data);
    String encodedData = Base64.getEncoder().encodeToString(data);
    String dataUriString = 
        "data:application/gltf-buffer;base64," + encodedData;
    
    buffer.setUri(dataUriString);
}
 
Example #12
Source File: SolutionSettingsControllerTest.java    From remote-monitoring-services-java with MIT License 6 votes vote down vote up
@Test(timeout = SolutionSettingsControllerTest.TIMEOUT)
@Category({UnitTest.class})
public void setLogoShouldReturnGivenLogo() throws BaseException, ExecutionException, InterruptedException, UnsupportedEncodingException, URISyntaxException {
    // Arrange
    String image = rand.NextString();
    String type = rand.NextString();
    Logo model = new Logo(image, type, null, false);
    setLogoMockSetup(model);
    controller = new SolutionSettingsController(mockStorage, mockActions);
    Http.Response mockResponse = TestUtils.setRequest(SolutionSettingsControllerTest.LOGO_BODY);

    // Act
    byte[] bytes = TestUtils.getBytes(controller.setLogoAsync().toCompletableFuture().get());
    byte[] bytesold = Base64.getDecoder().decode(model.getImage().getBytes());

    // Assert
    assertEquals(ByteString.fromArray(bytes), ByteString.fromArray(bytesold));
    Mockito.verify(mockResponse).setHeader(Logo.IS_DEFAULT_HEADER, Boolean.toString(false));
}
 
Example #13
Source File: IdentityUtil.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Generates a random number using two UUIDs and HMAC-SHA1
 *
 * @return Random Number generated.
 * @throws IdentityException Exception due to Invalid Algorithm or Invalid Key
 */
public static String getRandomNumber() throws IdentityException {
    try {
        String secretKey = UUIDGenerator.generateUUID();
        String baseString = UUIDGenerator.generateUUID();

        SecretKeySpec key = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(key);
        byte[] rawHmac = mac.doFinal(baseString.getBytes());
        String random = Base64.getEncoder().encodeToString(rawHmac);
        // Registry doesn't have support for these character.
        random = random.replace("/", "_");
        random = random.replace("=", "a");
        random = random.replace("+", "f");
        return random;
    } catch (Exception e) {
        log.error("Error when generating a random number.", e);
        throw IdentityException.error("Error when generating a random number.", e);
    }
}
 
Example #14
Source File: Base64GetEncoderTest.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
private static void testWrapEncode1(final Base64.Encoder encoder)
        throws IOException {
    System.err.println("\nEncoder.wrap test I ");

    final byte[] bytesIn = "fo".getBytes(US_ASCII);
    String base64EncodedString;
    ByteArrayOutputStream encodingStream = new ByteArrayOutputStream();
    OutputStream encoding = encoder.wrap(encodingStream);
    encoding.write(bytesIn);
    encoding.close();

    final byte[] encodedBytes = encodingStream.toByteArray();

    System.err.print("result = " + new String(encodedBytes, US_ASCII)
            + "  after the Base64 encoding \n");

    base64EncodedString = new String(encodedBytes, US_ASCII);

    if (base64EncodedString.contains("$$$")) {
        throw new RuntimeException(
                "Base64 encoding contains line separator after wrap I test ... \n");
    }
}
 
Example #15
Source File: WebhookBuilderDelegateImpl.java    From Javacord with Apache License 2.0 6 votes vote down vote up
@Override
public CompletableFuture<Webhook> create() {
    if (name == null) {
        throw new IllegalStateException("Name is no optional parameter!");
    }
    ObjectNode body = JsonNodeFactory.instance.objectNode();
    body.put("name", name);
    if (avatar != null) {
        return avatar.asByteArray(channel.getApi()).thenAccept(bytes -> {
            String base64Avatar = "data:image/" + avatar.getFileType() + ";base64,"
                    + Base64.getEncoder().encodeToString(bytes);
            body.put("avatar", base64Avatar);
        }).thenCompose(aVoid ->
                new RestRequest<Webhook>(channel.getApi(), RestMethod.POST, RestEndpoint.CHANNEL_WEBHOOK)
                        .setUrlParameters(channel.getIdAsString())
                        .setBody(body)
                        .setAuditLogReason(reason)
                        .execute(result -> new WebhookImpl(channel.getApi(), result.getJsonBody())));
    }
    return new RestRequest<Webhook>(channel.getApi(), RestMethod.POST, RestEndpoint.CHANNEL_WEBHOOK)
            .setUrlParameters(channel.getIdAsString())
            .setBody(body)
            .setAuditLogReason(reason)
            .execute(result -> new WebhookImpl(channel.getApi(), result.getJsonBody()));
}
 
Example #16
Source File: ComponentProxyCustomizerTest.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Test
public void testSend() throws Exception {
    assertThat(context.getBean("my-bean", MyBean.class)).isNotNull();

    final ProducerTemplate template = camelContext.createProducerTemplate();
    final MockEndpoint mock = camelContext.getEndpoint("mock:result", MockEndpoint.class);
    final String body = "hello";
    final String expected = Base64.getEncoder().encodeToString("HELLO WORLD!".getBytes(StandardCharsets.US_ASCII));

    mock.expectedMessageCount(1);
    mock.expectedBodiesReceived(expected);

    template.sendBody("direct:start", body);

    mock.assertIsSatisfied();
}
 
Example #17
Source File: VarbinaryFunctions.java    From presto with Apache License 2.0 5 votes vote down vote up
@Description("Decode URL safe base64 encoded binary data")
@ScalarFunction("from_base64url")
@SqlType(StandardTypes.VARBINARY)
public static Slice fromBase64UrlVarbinary(@SqlType(StandardTypes.VARBINARY) Slice slice)
{
    try {
        if (slice.hasByteArray()) {
            return Slices.wrappedBuffer(Base64.getUrlDecoder().decode(slice.toByteBuffer()));
        }
        return Slices.wrappedBuffer(Base64.getUrlDecoder().decode(slice.getBytes()));
    }
    catch (IllegalArgumentException e) {
        throw new PrestoException(INVALID_FUNCTION_ARGUMENT, e);
    }
}
 
Example #18
Source File: UnstructuredName.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    PKCS10 req = new PKCS10(Base64.getMimeDecoder().decode(csrStr));

    // If PKCS9Attribute did not accept the PrintableString ASN.1 tag,
    // this would fail with an IOException
    Object attr = req.getAttributes().getAttribute("1.2.840.113549.1.9.2");

    // Check that the attribute exists
    if (attr == null) {
        throw new Exception("Attribute should not be null.");
    }

    System.out.println("Test passed.");
}
 
Example #19
Source File: AbstractWSHandler7.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected String generateAcceptKey(String key ){
    StringBuilder builder = new StringBuilder( key );
    builder.append(SALT);
    try {
        return Base64.getEncoder().encodeToString( MessageDigest.getInstance(
                "SHA").digest(builder.toString().getBytes(  // NOI18N
                        Charset.forName(Utils.UTF_8))));
    }
    catch (NoSuchAlgorithmException e) {
        WebSocketServerImpl.LOG.log(Level.WARNING, null , e);
        return null;
    }
}
 
Example #20
Source File: Base64BinaryTest.java    From XACML with MIT License 5 votes vote down vote up
@Test
public void test() throws DecoderException {
  Base64Binary binary = new Base64Binary(null);
  assertNull(binary.getData());
  assertNull(binary.stringValue());
  assertEquals("{}", binary.toString());
  assertEquals(0, binary.hashCode());
  assertFalse(binary.equals(null));
  assertFalse(binary.equals(new Object()));
  assertTrue(binary.equals(binary));
  String data = "I am base 64";
  String r = Base64.getEncoder().encodeToString(data.getBytes());
  binary = Base64Binary.newInstance(r);
  assertNotEquals("{}", binary.toString());
  assertNotNull(binary.toString());
  assertNull(Base64Binary.newInstance(null));
  assertEquals(r, binary.stringValue());
  Base64Binary binary2 = new Base64Binary(binary.getData());
  assertEquals(binary, binary2);
  binary = new Base64Binary(null);
  binary2 = new Base64Binary(null);
  assertEquals(binary, binary2);
  binary2 = Base64Binary.newInstance(r);
  assertNotEquals(binary, binary2);
  assertNotEquals(binary2, binary);
  binary = Base64Binary.newInstance(r);
  assertTrue(binary.hashCode() != 0);
}
 
Example #21
Source File: Base64Test.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Checks decoding of bytes containing a value outside of the allowed
 * {@link #TABLE_1 "basic" alphabet}.
 */
public void testDecoder_extraChars_basic() throws Exception {
    Decoder basicDecoder = Base64.getDecoder(); // uses Table 1
    // Check failure cases common to both RFC4648 Table 1 and Table 2 decoding.
    checkDecoder_extraChars_common(basicDecoder);

    // Tests characters that are part of RFC4848 Table 2 but not Table 1.
    assertDecodeThrowsIAe(basicDecoder, "_aGVsbG8sIHdvcmx");
    assertDecodeThrowsIAe(basicDecoder, "aGV_sbG8sIHdvcmx");
    assertDecodeThrowsIAe(basicDecoder, "aGVsbG8sIHdvcmx_");
}
 
Example #22
Source File: FtpClient.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
private byte[] getSecurityData() {
    String s = getLastResponseString();
    if (s.substring(4, 9).equalsIgnoreCase("ADAT=")) {
        // Need to get rid of the leading '315 ADAT='
        // and the trailing newline
        return Base64.getMimeDecoder().decode(s.substring(9, s.length() - 1));
    }
    return null;
}
 
Example #23
Source File: PasswordCrypt.java    From erflute with Apache License 2.0 5 votes vote down vote up
public static String encrypt(String password) throws Exception {
    final Key key = getKey();

    final Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
    cipher.init(Cipher.ENCRYPT_MODE, key);

    final byte[] input = password.getBytes();
    final byte[] encrypted = cipher.doFinal(input);

    return Base64.getEncoder().encodeToString(encrypted);
}
 
Example #24
Source File: Types.java    From gef with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Serializes a given {@link TypeToken} into a {@link String}
 * representation.
 *
 * @param typeToken
 *            The {@link TypeToken} to serialize.
 * @return The string representation of the {@link TypeToken} encoded in
 *         Base64.
 */
public static final String serialize(TypeToken<?> typeToken) {
	try {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ObjectOutputStream os = new ObjectOutputStream(bos);
		os.writeObject(typeToken);
		os.close();
		return Base64.getEncoder().encodeToString(bos.toByteArray());
	} catch (IOException e) {
		throw new IllegalArgumentException(
				"Could not serialize " + typeToken);
	}
}
 
Example #25
Source File: RsaPublicKeyFilter.java    From mPaaS with Apache License 2.0 5 votes vote down vote up
/**
 * RSA publickey相关操作
 *
 * @param request
 * @param response
 * @param pubKey
 */
private void handleTenant(HttpServletRequest request,
                          HttpServletResponse response,
                          String pubKey) {
    if (RSA_KEY.equals(pubKey)) {
        if(base64PublicKey==null) {
            //publicCode base64 编码
            //由于配置文件中的RSA 密钥是Hex 编码,需要转换
            if (StringUtils.isNotBlank(systemConfig.getPublicCode())) {
                base64PublicKey= Base64.getEncoder().encodeToString(Hex.decode(systemConfig.getPublicCode()));
            }
        }
        response.setHeader(HEADER_PUBKEY, base64PublicKey);
    }
}
 
Example #26
Source File: ImageSegmentBlurLayout.java    From Alice-LiveMan with GNU Affero General Public License v3.0 5 votes vote down vote up
public String getImageBase64() {
    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", bos);
        return imageHeader + Base64.getEncoder().encodeToString(bos.toByteArray());
    } catch (Exception e) {
        log.error("encode imageBase64 failed", e);
    }
    return null;
}
 
Example #27
Source File: BValue.java    From gridgo with MIT License 5 votes vote down vote up
default BValue encodeBase64() {
    if (!(this.getData() instanceof byte[])) {
        throw new InvalidTypeException("Cannot encode base64 from data which is not in raw (byte[]) format");
    }
    this.setData(Base64.getEncoder().encodeToString(getRaw()));
    return this;
}
 
Example #28
Source File: JwtManager.java    From onlyoffice-confluence with GNU Affero General Public License v3.0 5 votes vote down vote up
public String createToken(JSONObject payload) throws Exception {
    JSONObject header = new JSONObject();
    header.put("alg", "HS256");
    header.put("typ", "JWT");

    Encoder enc = Base64.getUrlEncoder();

    String encHeader = enc.encodeToString(header.toString().getBytes("UTF-8")).replace("=", "");
    String encPayload = enc.encodeToString(payload.toString().getBytes("UTF-8")).replace("=", "");
    String hash = calculateHash(encHeader, encPayload);

    return encHeader + "." + encPayload + "." + hash;
}
 
Example #29
Source File: PrivDistributeRawTransactionTest.java    From besu with Apache License 2.0 5 votes vote down vote up
@Test
public void validTransactionHashReturnedAfterDistribute() {
  final String enclavePublicKey = "93Ky7lXwFkMc7+ckoFgUMku5bpr9tz4zhmWmk9RlNng=";
  when(privacyController.sendTransaction(any(PrivateTransaction.class), any(), any()))
      .thenReturn(enclavePublicKey);
  when(privacyController.validatePrivateTransaction(any(PrivateTransaction.class), anyString()))
      .thenReturn(ValidationResult.valid());

  final JsonRpcRequestContext request =
      new JsonRpcRequestContext(
          new JsonRpcRequest(
              "2.0",
              "priv_distributeRawTransaction",
              new String[] {VALID_PRIVATE_TRANSACTION_RLP_PRIVACY_GROUP}),
          user);

  final JsonRpcResponse expectedResponse =
      new JsonRpcSuccessResponse(
          request.getRequest().getId(),
          Bytes.wrap(Base64.getDecoder().decode(enclavePublicKey)).toString());

  final JsonRpcResponse actualResponse = method.response(request);

  assertThat(actualResponse).isEqualToComparingFieldByField(expectedResponse);
  verify(privacyController)
      .sendTransaction(any(PrivateTransaction.class), eq(ENCLAVE_PUBLIC_KEY), any());
  verify(privacyController)
      .validatePrivateTransaction(any(PrivateTransaction.class), eq(ENCLAVE_PUBLIC_KEY));
}
 
Example #30
Source File: Encrypter.java    From stash-token-auth with GNU General Public License v3.0 5 votes vote down vote up
public String decrypt(String value) throws EncryptionException {
  try {
    byte[] dec = Base64.getDecoder().decode(value.getBytes());
    byte[] utf8 = dcipher.doFinal(dec);
    return new String(utf8, "UTF8");
  } catch (UnsupportedEncodingException | BadPaddingException | IllegalBlockSizeException e) {
    throw new EncryptionException("Could not decrypt string", e);
  }
}