Java Code Examples for org.apache.commons.codec.binary.Base64#decodeBase64()

The following examples show how to use org.apache.commons.codec.binary.Base64#decodeBase64() . 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: U2FAuthenticationResponse.java    From fido2 with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 *
 * @param appParam
 * @param userpresence
 * @param counterValue
 * @param challParam
 * @return
 */
public static String objectTBS(String appParam, byte userpresence, int counterValue, String challParam) {

    byte[] appparam = Base64.decodeBase64(appParam);
    int apL = appparam.length;
    byte[] challparam = Base64.decodeBase64(challParam);
    int cpL = challparam.length;

    byte[] ob2sign = new byte[apL + 1 + skfsConstants.COUNTER_VALUE_BYTES + cpL];
    int tot = 0;

    System.arraycopy(appparam, 0, ob2sign, 0, apL);
    tot += apL;
    ob2sign[tot] = userpresence;
    tot++;
    System.arraycopy(int2bytearray(counterValue), 0, ob2sign, tot, 4);
    tot += 4;
    System.arraycopy(challparam, 0, ob2sign, tot, cpL);
    tot += cpL;

    return Base64.encodeBase64String(ob2sign);
}
 
Example 2
Source File: ReflexDB.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
private static ReflexActionSendProtocol convertPc(JsonObject pr, JsonDeserializationContext context) {
   ReflexActionSendProtocol.Type typ;
   switch (pr.get("p").getAsString()) {
   case "ZW":
      typ = ReflexActionSendProtocol.Type.ZWAVE;
      break;
   case "ZB":
      typ = ReflexActionSendProtocol.Type.ZIGBEE;
      break;
   default:
      throw new RuntimeException("unknown send protocol type: " + pr.get("p"));
   }

   byte[] msg = Base64.decodeBase64(pr.get("m").getAsString());
   return new ReflexActionSendProtocol(typ, msg);
}
 
Example 3
Source File: ActionIcon.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
ActionResult<Wo> execute(EffectivePerson effectivePerson, String id) throws Exception {
	try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
		Business business = new Business(emc);
		ActionResult<Wo> result = new ActionResult<>();
		Portal o = business.portal().pick(id);
		if (null == o) {
			throw new ExceptionPortalNotExist(id);
		}
		// if (!business.portal().visible(effectivePerson, o)) {
		// throw new
		// ExceptionPortalAccessDenied(effectivePerson.getDistinguishedName(),
		// o.getName(), o.getId());
		// }
		byte[] bs = Base64
				.decodeBase64(StringUtils.isEmpty(o.getIcon()) ? DEFAULT_PORTAL_ICON_BASE64 : o.getIcon());
		Wo wo = new Wo(bs, this.contentType(false, "icon.png"), this.contentDisposition(false, "icon.png"));
		result.setData(wo);
		return result;
	}
}
 
Example 4
Source File: OAuth2Util.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public static String getUserIdFromAccessToken(String apiKey) {
    String userId = null;
    String decodedKey = new String(Base64.decodeBase64(apiKey.getBytes(Charsets.UTF_8)), Charsets.UTF_8);
    String[] tmpArr = decodedKey.split(":");
    if (tmpArr != null) {
        userId = tmpArr[1];
    }
    return userId;
}
 
Example 5
Source File: WebPage.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
public File getRecording(String fileName) throws IOException {
  browser.executeScript("kurentoTest.recordingToData();");
  String recording = getProperty("recordingData").toString();

  // Base64 to File
  File outputFile = new File(fileName);
  byte[] bytes = Base64.decodeBase64(recording.substring(recording.lastIndexOf(",") + 1));
  FileUtils.writeByteArrayToFile(outputFile, bytes);

  return outputFile;
}
 
Example 6
Source File: JWTTest.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldCreateAnEmptyECDSA384SignedToken() throws Exception {
    String signed = JWT.create().sign(Algorithm.ECDSA384((ECKey) PemUtils.readPrivateKeyFromFile(PRIVATE_KEY_FILE_EC_384, "EC")));
    assertThat(signed, is(notNullValue()));

    String[] parts = signed.split("\\.");
    String headerJson = new String(Base64.decodeBase64(parts[0]), StandardCharsets.UTF_8);
    assertThat(headerJson, JsonMatcher.hasEntry("alg", "ES384"));
    assertThat(headerJson, JsonMatcher.hasEntry("typ", "JWT"));
    assertThat(parts[1], is("e30"));

    JWTVerifier verified = JWT.require(Algorithm.ECDSA384((ECKey) PemUtils.readPublicKeyFromFile(PUBLIC_KEY_FILE_EC_384, "EC")))
            .build();
    assertThat(verified, is(notNullValue()));
}
 
Example 7
Source File: CassandraDataHandler.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
private ByteBuffer base64DecodeByteBuffer(String data) throws ODataServiceFault {
    try {
        byte[] buff = Base64.decodeBase64(data.getBytes(DBConstants.DEFAULT_CHAR_SET_TYPE));
        ByteBuffer result = ByteBuffer.allocate(buff.length);
        result.put(buff);
        return result;
    } catch (UnsupportedEncodingException e) {
        throw new ODataServiceFault(e, "Error in decoding input base64 data: " + e.getMessage());
    }
}
 
Example 8
Source File: AESEncryption.java    From amazon-cognito-developer-authentication-sample with Apache License 2.0 5 votes vote down vote up
/**
 * Decrypt a string with given key.
 * 
 * @param cipherText
 *            encrypted string
 * @param key
 *            the key used in decryption
 * @return a decrypted string
 */
public static String unwrap(String cipherText, String key) {
    byte[] dataToDecrypt = Base64.decodeBase64(cipherText.getBytes());
    byte[] iv = new byte[16];
    byte[] data = new byte[dataToDecrypt.length - 16];

    System.arraycopy(dataToDecrypt, 0, iv, 0, 16);
    System.arraycopy(dataToDecrypt, 16, data, 0, dataToDecrypt.length - 16);

    byte[] plainText = decrypt(data, key, iv);
    return new String(plainText);
}
 
Example 9
Source File: RedisCacheWrapper.java    From ymate-platform-v2 with Apache License 2.0 5 votes vote down vote up
private Object __doUnserializeValue(String value) throws Exception {
    if (value == null) {
        return null;
    }
    byte[] _bytes = Base64.decodeBase64(value);
    return __owner.getModuleCfg().getSerializer().deserialize(_bytes, Object.class);
}
 
Example 10
Source File: BCodec.java    From text_converter with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected byte[] doDecoding(final byte[] bytes) {
    if (bytes == null) {
        return null;
    }
    return Base64.decodeBase64(bytes);
}
 
Example 11
Source File: ProtocolMessage.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] computeBuffer() {
   if (encoded == null) {
      return null;
   }

   return Base64.decodeBase64(encoded);
}
 
Example 12
Source File: RegisteredServiceEditBean.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
/**
 * Configure username attribute provider.
 *
 * @param provider the provider
 * @param uBean the u bean
 */
private static void configureUsernameAttributeProvider(final RegisteredServiceUsernameAttributeProvider provider,
                                                       final RegisteredServiceUsernameAttributeProviderEditBean uBean) {
    if (provider instanceof DefaultRegisteredServiceUsernameProvider) {
        uBean.setType(RegisteredServiceUsernameAttributeProviderEditBean.Types.DEFAULT.toString());
    } else if (provider instanceof AnonymousRegisteredServiceUsernameAttributeProvider) {
        final AnonymousRegisteredServiceUsernameAttributeProvider anonymous =
                (AnonymousRegisteredServiceUsernameAttributeProvider) provider;
        uBean.setType(RegisteredServiceUsernameAttributeProviderEditBean.Types.ANONYMOUS.toString());
        final PersistentIdGenerator generator = anonymous.getPersistentIdGenerator();
        if (generator instanceof ShibbolethCompatiblePersistentIdGenerator) {
            final ShibbolethCompatiblePersistentIdGenerator sh =
                    (ShibbolethCompatiblePersistentIdGenerator) generator;

            String salt = new String(sh.getSalt(), Charset.defaultCharset());
            if (Base64.isBase64(salt)) {
                salt = new String(Base64.decodeBase64(salt));
            }

            uBean.setValue(salt);
        }
    } else if (provider instanceof PrincipalAttributeRegisteredServiceUsernameProvider) {
        final PrincipalAttributeRegisteredServiceUsernameProvider p =
                (PrincipalAttributeRegisteredServiceUsernameProvider) provider;
        uBean.setType(RegisteredServiceUsernameAttributeProviderEditBean.Types.ATTRIBUTE.toString());
        uBean.setValue(p.getUsernameAttribute());
    }
}
 
Example 13
Source File: JSONIntermediateDataFormat.java    From sqoop-on-spark with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private Object[] toObject(JSONObject json) {

  if (json == null) {
    return null;
  }
  Column[] columns = schema.getColumnsArray();
  Object[] object = new Object[columns.length];

  Set<String> jsonKeyNames = json.keySet();
  for (String name : jsonKeyNames) {
    Integer nameIndex = schema.getColumnNameIndex(name);
    Column column = columns[nameIndex];

    Object obj = json.get(name);
    // null is a possible value
    if (obj == null && !column.isNullable()) {
      throw new SqoopException(IntermediateDataFormatError.INTERMEDIATE_DATA_FORMAT_0005,
          column.getName() + " does not support null values");
    }
    if (obj == null) {
      object[nameIndex] = null;
      continue;
    }
    switch (column.getType()) {
    case ARRAY:
    case SET:
      object[nameIndex] = toList((JSONArray) obj).toArray();
      break;
    case MAP:
      object[nameIndex] = toMap((JSONObject) obj);
      break;
    case ENUM:
    case TEXT:
      object[nameIndex] = toText(obj.toString());
      break;
    case BINARY:
    case UNKNOWN:
      // JSON spec is to store byte array as base64 encoded
      object[nameIndex] = Base64.decodeBase64(obj.toString());
      break;
    case FIXED_POINT:
      object[nameIndex] = toFixedPoint(obj.toString(), column);
      break;
    case FLOATING_POINT:
      object[nameIndex] = toFloatingPoint(obj.toString(), column);
      break;
    case DECIMAL:
      object[nameIndex] = toDecimal(obj.toString(), column);
      break;
    case DATE:
      object[nameIndex] = toDate(obj.toString(), column);
      break;
    case TIME:
      object[nameIndex] = toTime(obj.toString(), column);
      break;
    case DATE_TIME:
      object[nameIndex] = toDateTime(obj.toString(), column);
      break;
    case BIT:
      object[nameIndex] = toBit(obj.toString());
      break;
    default:
      throw new SqoopException(IntermediateDataFormatError.INTERMEDIATE_DATA_FORMAT_0001,
          "Column type from schema was not recognized for " + column.getType());
    }
  }
  return object;
}
 
Example 14
Source File: SsRtbCrypter.java    From bidder with Apache License 2.0 4 votes vote down vote up
public long decodeDecrypt(String base64Websafe, SecretKey encryptKey, SecretKey integrityKey) throws SsRtbDecryptingException {
  String base64NonWebsafe = base64Websafe.replace("-", "+").replace("_", "/") + "==";
  byte[] encrypted = Base64.decodeBase64(base64NonWebsafe.getBytes(US_ASCII));
  byte[] decrypted = decrypt(encrypted, encryptKey, integrityKey);
  return toLong(decrypted);
}
 
Example 15
Source File: RSAKeyLoader.java    From library with Apache License 2.0 4 votes vote down vote up
private PrivateKey getPrivateKeyFromString(String key) throws NoSuchAlgorithmException, InvalidKeySpecException {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(key));
        PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
        return privateKey;
}
 
Example 16
Source File: ConsoleProxyPasswordBasedEncryptor.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
public byte[] getKeyBytes() {
    return Base64.decodeBase64(base64EncodedKeyBytes);
}
 
Example 17
Source File: SecurityFilter.java    From maven-framework-project with MIT License 4 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) {
	ResourceMethodInvoker methodInvoker = (ResourceMethodInvoker) requestContext
			.getProperty(RESOURCE_METHOD_INVOKER);
	Method method = methodInvoker.getMethod();
	// Access allowed for all
	if (!method.isAnnotationPresent(PermitAll.class)) {
		// Access denied for all
		if (method.isAnnotationPresent(DenyAll.class)) {
			requestContext.abortWith(ACCESS_FORBIDDEN);
			return;
		}

		// Get request headers
		final MultivaluedMap<String, String> headersMap = requestContext.getHeaders();

		// Fetch authorization header
		final List<String> authorizationList = headersMap.get(AUTHORIZATION_PROPERTY);

		// If no authorization information present; block access
		if (authorizationList == null || authorizationList.isEmpty()) {
			requestContext.abortWith(ACCESS_DENIED);
			return;
		}

		// Get encoded username and password
		final String encodedUserPassword = authorizationList.get(0).replaceFirst(AUTHENTICATION_SCHEME + " ", "");

		// Decode username and password
		String usernameAndPassword = new String(Base64.decodeBase64(encodedUserPassword));

		// Split username and password tokens
		final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":");
		final String userName = tokenizer.nextToken();
		final String password = tokenizer.nextToken();

		// Verify user access
		if (method.isAnnotationPresent(RolesAllowed.class)) {
			RolesAllowed rolesAnnotation = method.getAnnotation(RolesAllowed.class);
			Set<String> rolesSet = new HashSet<String>(Arrays.asList(rolesAnnotation.value()));

			// Is user valid?
			if (!isUserAllowed(userName, password, rolesSet)) {
				requestContext.abortWith(ACCESS_DENIED);
				return;
			}
		}
	}
}
 
Example 18
Source File: MimeContent.java    From ews-java-api with MIT License 2 votes vote down vote up
/**
 * Reads text value from XML.
 *
 * @param reader the reader
 * @throws XMLStreamException the XML stream exception
 * @throws ServiceXmlDeserializationException the service xml deserialization exception
 */
@Override
public void readTextValueFromXml(EwsServiceXmlReader reader)
    throws XMLStreamException, ServiceXmlDeserializationException {
  this.content = Base64.decodeBase64(reader.readValue());
}
 
Example 19
Source File: EncryptionUtils.java    From tools with MIT License 2 votes vote down vote up
/**
 * BASE64 decode
 *
 * @param content content
 * @return decrypted
 */
public static String decodeBase64(String content) {
    return new String(Base64.decodeBase64(content));
}
 
Example 20
Source File: PacketUtil.java    From trex-stateless-gui with Apache License 2.0 2 votes vote down vote up
/**
 * Get packet from encoded string
 *
 * @param encodedBinaryPacket
 * @return packet
 * @throws IllegalRawDataException
 */
public Packet getPacketFromEncodedString(String encodedBinaryPacket) throws IllegalRawDataException {
    byte[] pkt = Base64.decodeBase64(encodedBinaryPacket);
    return EthernetPacket.newPacket(pkt, 0, pkt.length);
}