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

The following examples show how to use org.apache.tomcat.util.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: SignCode.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Removes base64 encoding, unzips the files and writes the new files over
 * the top of the old ones.
 */
private static void extractFilesFromApplicationString(String data, List<File> files)
        throws IOException {
    ByteArrayInputStream bais = new ByteArrayInputStream(Base64.decodeBase64(data));
    try (ZipInputStream zis = new ZipInputStream(bais)) {
        byte[] buf = new byte[32 * 1024];
        for (int i = 0; i < files.size(); i ++) {
            try (FileOutputStream fos = new FileOutputStream(files.get(i))) {
                zis.getNextEntry();
                int numRead;
                while ( (numRead = zis.read(buf)) >= 0) {
                    fos.write(buf, 0 , numRead);
                }
            }
        }
    }
}
 
Example 2
Source File: OrganizationController.java    From C4SG-Obsolete with MIT License 6 votes vote down vote up
@RequestMapping(value = "/{id}/uploadLogo", method = RequestMethod.POST)
@ApiOperation(value = "Add new upload Logo")
public String uploadLogo(@ApiParam(value = "Organization Id", required = true)
                         @PathVariable Integer id,
                         @ApiParam(value = "Request Body", required = true)
                         @RequestBody String logoFileContent) {
    try {
        byte[] imageByte = Base64.decodeBase64(logoFileContent);
        File directory = new File(LOGO_UPLOAD.getValue());
        if (!directory.exists()) {
            directory.mkdir();
        }
        File f = new File(organizationService.getLogoUploadPath(id));
        new FileOutputStream(f).write(imageByte);
        return "Success";
    } catch (Exception e) {
        return "Error saving logo for organization " + id + " : " + e;
    }
}
 
Example 3
Source File: DesUtil.java    From javabase with Apache License 2.0 6 votes vote down vote up
/**
 * 带向量的解密
 * @param str
 * @param secretKey
 * @param iv
 * @return
    * @throws Exception
    */
public static String decrypt(String str, String secretKey, byte[] iv) throws Exception {
	if (str == null || "".equals(str)) {
		return str;
	}
	String str1 = URLDecoder.decode(str, "UTF-8");
	byte str2[] = Base64.decodeBase64(str1.getBytes());
	IvParameterSpec zeroIv = new IvParameterSpec(iv);
	SecretKeySpec key = new SecretKeySpec(secretKey.getBytes("UTF-8"), "DES");
	Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
	cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);
	byte[] str3 = cipher.doFinal(str2);
	String res = str;
	if (str3 != null) {
		res = new String(str3, "UTF-8");
	}
	return res;
}
 
Example 4
Source File: BasicAuthenticator.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private byte[] parseBase64() throws IllegalArgumentException {
    byte[] decoded = Base64.decodeBase64(
                authorization.getBuffer(),
                base64blobOffset, base64blobLength);
    //  restore original offset
    authorization.setOffset(initialOffset);
    if (decoded == null) {
        throw new IllegalArgumentException(
                "Basic Authorization credentials are not Base64");
    }
    return decoded;
}
 
Example 5
Source File: AesUtil.java    From base-admin with MIT License 5 votes vote down vote up
/**
 * 解密
 *
 * @param encryptStr 解密的字符串
 * @param decryptKey 解密的key值
 */
public static String decrypt(String encryptStr, String decryptKey) throws Exception {
    //base64格式的key字符串转byte
    byte[] decodeBase64 = Base64.decodeBase64(encryptStr);

    //设置Cipher对象
    Cipher cipher = Cipher.getInstance(ALGORITHMS,PROVIDER);
    cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), KEY_ALGORITHM));

    //调用doFinal解密
    return new String(cipher.doFinal(decodeBase64));
}
 
Example 6
Source File: MimeUtility.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
/**
 * Parse a string using the RFC 2047 rules for an "encoded-word"
 * type.  This encoding has the syntax:
 *
 * encoded-word = "=?" charset "?" encoding "?" encoded-text "?="
 *
 * @param word   The possibly encoded word value.
 *
 * @return The decoded word.
 * @throws ParseException
 * @throws UnsupportedEncodingException
 */
private static String decodeWord(String word) throws ParseException, UnsupportedEncodingException {
    // encoded words start with the characters "=?".  If this not an encoded word, we throw a
    // ParseException for the caller.

    if (!word.startsWith(ENCODED_TOKEN_MARKER)) {
        throw new ParseException("Invalid RFC 2047 encoded-word: " + word);
    }

    int charsetPos = word.indexOf('?', 2);
    if (charsetPos == -1) {
        throw new ParseException("Missing charset in RFC 2047 encoded-word: " + word);
    }

    // pull out the character set information (this is the MIME name at this point).
    String charset = word.substring(2, charsetPos).toLowerCase(Locale.ENGLISH);

    // now pull out the encoding token the same way.
    int encodingPos = word.indexOf('?', charsetPos + 1);
    if (encodingPos == -1) {
        throw new ParseException("Missing encoding in RFC 2047 encoded-word: " + word);
    }

    String encoding = word.substring(charsetPos + 1, encodingPos);

    // and finally the encoded text.
    int encodedTextPos = word.indexOf(ENCODED_TOKEN_FINISHER, encodingPos + 1);
    if (encodedTextPos == -1) {
        throw new ParseException("Missing encoded text in RFC 2047 encoded-word: " + word);
    }

    String encodedText = word.substring(encodingPos + 1, encodedTextPos);

    // seems a bit silly to encode a null string, but easy to deal with.
    if (encodedText.length() == 0) {
        return "";
    }

    try {
        // the decoder writes directly to an output stream.
        ByteArrayOutputStream out = new ByteArrayOutputStream(encodedText.length());

        byte[] decodedData;
        // Base64 encoded?
        if (encoding.equals(BASE64_ENCODING_MARKER)) {
            decodedData = Base64.decodeBase64(encodedText);
        } else if (encoding.equals(QUOTEDPRINTABLE_ENCODING_MARKER)) { // maybe quoted printable.
            byte[] encodedData = encodedText.getBytes(US_ASCII_CHARSET);
            QuotedPrintableDecoder.decode(encodedData, out);
            decodedData = out.toByteArray();
        } else {
            throw new UnsupportedEncodingException("Unknown RFC 2047 encoding: " + encoding);
        }
        // Convert decoded byte data into a string.
        return new String(decodedData, javaCharset(charset));
    } catch (IOException e) {
        throw new UnsupportedEncodingException("Invalid RFC 2047 encoding");
    }
}
 
Example 7
Source File: PEMFile.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
private byte[] decode() {
    return Base64.decodeBase64(content);
}
 
Example 8
Source File: JWTUtils.java    From spring-boot-example with MIT License 4 votes vote down vote up
public static SecretKey getKey(String secret){

        byte[] encodedKey = Base64.decodeBase64(secret);
        // 根据给定的字节数组使用AES加密算法构造一个密钥,使用 encodedKey中的始于且包含 0 到前 leng 个字节这是当然是所有。(后面的文章中马上回推出讲解Java加密和解密的一些算法)
        return new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
    }
 
Example 9
Source File: BasicAuthenticator.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
/**
 * Authenticate the user making this request, based on the specified
 * login configuration.  Return <code>true</code> if any specified
 * constraint has been satisfied, or <code>false</code> if we have
 * created a response challenge already.
 *
 * @param request Request we are processing
 * @param response Response we are creating
 * @param config    Login configuration describing how authentication
 *              should be performed
 *
 * @exception IOException if an input/output error occurs
 */
@Override
public boolean authenticate(Request request,
                            HttpServletResponse response,
                            LoginConfig config)
    throws IOException {

    if (checkForCachedAuthentication(request, response, true)) {
        return true;
    }

    // Validate any credentials already included with this request
    String username = null;
    String password = null;

    MessageBytes authorization = 
        request.getCoyoteRequest().getMimeHeaders()
        .getValue("authorization");
    
    if (authorization != null) {
        authorization.toBytes();
        ByteChunk authorizationBC = authorization.getByteChunk();
        if (authorizationBC.startsWithIgnoreCase("basic ", 0)) {
            authorizationBC.setOffset(authorizationBC.getOffset() + 6);
            
            byte[] decoded = Base64.decodeBase64(
                    authorizationBC.getBuffer(),
                    authorizationBC.getOffset(),
                    authorizationBC.getLength());
            
            // Get username and password
            int colon = -1;
            for (int i = 0; i < decoded.length; i++) {
                if (decoded[i] == ':') {
                    colon = i;
                    break;
                }
            }

            if (colon < 0) {
                username = new String(decoded, B2CConverter.ISO_8859_1);
            } else {
                username = new String(
                        decoded, 0, colon, B2CConverter.ISO_8859_1);
                password = new String(
                        decoded, colon + 1, decoded.length - colon - 1,
                        B2CConverter.ISO_8859_1);
            }
            
            authorizationBC.setOffset(authorizationBC.getOffset() - 6);
        }

        Principal principal = context.getRealm().authenticate(username, password);
        if (principal != null) {
            register(request, response, principal,
                    HttpServletRequest.BASIC_AUTH, username, password);
            return (true);
        }
    }
    
    StringBuilder value = new StringBuilder(16);
    value.append("Basic realm=\"");
    if (config.getRealmName() == null) {
        value.append(REALM_NAME);
    } else {
        value.append(config.getRealmName());
    }
    value.append('\"');        
    response.setHeader(AUTH_HEADER_NAME, value.toString());
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    return (false);

}
 
Example 10
Source File: MimeUtility.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
/**
 * Parse a string using the RFC 2047 rules for an "encoded-word"
 * type.  This encoding has the syntax:
 *
 * encoded-word = "=?" charset "?" encoding "?" encoded-text "?="
 *
 * @param word   The possibly encoded word value.
 *
 * @return The decoded word.
 * @throws ParseException
 * @throws UnsupportedEncodingException
 */
private static String decodeWord(String word) throws ParseException, UnsupportedEncodingException {
    // encoded words start with the characters "=?".  If this not an encoded word, we throw a
    // ParseException for the caller.

    if (!word.startsWith(ENCODED_TOKEN_MARKER)) {
        throw new ParseException("Invalid RFC 2047 encoded-word: " + word);
    }

    int charsetPos = word.indexOf('?', 2);
    if (charsetPos == -1) {
        throw new ParseException("Missing charset in RFC 2047 encoded-word: " + word);
    }

    // pull out the character set information (this is the MIME name at this point).
    String charset = word.substring(2, charsetPos).toLowerCase(Locale.ENGLISH);

    // now pull out the encoding token the same way.
    int encodingPos = word.indexOf('?', charsetPos + 1);
    if (encodingPos == -1) {
        throw new ParseException("Missing encoding in RFC 2047 encoded-word: " + word);
    }

    String encoding = word.substring(charsetPos + 1, encodingPos);

    // and finally the encoded text.
    int encodedTextPos = word.indexOf(ENCODED_TOKEN_FINISHER, encodingPos + 1);
    if (encodedTextPos == -1) {
        throw new ParseException("Missing encoded text in RFC 2047 encoded-word: " + word);
    }

    String encodedText = word.substring(encodingPos + 1, encodedTextPos);

    // seems a bit silly to encode a null string, but easy to deal with.
    if (encodedText.length() == 0) {
        return "";
    }

    try {
        // the decoder writes directly to an output stream.
        ByteArrayOutputStream out = new ByteArrayOutputStream(encodedText.length());

        byte[] decodedData;
        // Base64 encoded?
        if (encoding.equals(BASE64_ENCODING_MARKER)) {
            decodedData = Base64.decodeBase64(encodedText);
        } else if (encoding.equals(QUOTEDPRINTABLE_ENCODING_MARKER)) { // maybe quoted printable.
            byte[] encodedData = encodedText.getBytes(US_ASCII_CHARSET);
            QuotedPrintableDecoder.decode(encodedData, out);
            decodedData = out.toByteArray();
        } else {
            throw new UnsupportedEncodingException("Unknown RFC 2047 encoding: " + encoding);
        }
        // Convert decoded byte data into a string.
        return new String(decodedData, javaCharset(charset));
    } catch (IOException e) {
        throw new UnsupportedEncodingException("Invalid RFC 2047 encoding");
    }
}
 
Example 11
Source File: BasicAuthenticator.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
/**
 * Authenticate the user making this request, based on the specified
 * login configuration.  Return <code>true</code> if any specified
 * constraint has been satisfied, or <code>false</code> if we have
 * created a response challenge already.
 *
 * @param request Request we are processing
 * @param response Response we are creating
 * @param config    Login configuration describing how authentication
 *              should be performed
 *
 * @exception IOException if an input/output error occurs
 */
@Override
public boolean authenticate(Request request,
                            HttpServletResponse response,
                            LoginConfig config)
    throws IOException {

    if (checkForCachedAuthentication(request, response, true)) {
        return true;
    }

    // Validate any credentials already included with this request
    String username = null;
    String password = null;

    MessageBytes authorization = 
        request.getCoyoteRequest().getMimeHeaders()
        .getValue("authorization");
    
    if (authorization != null) {
        authorization.toBytes();
        ByteChunk authorizationBC = authorization.getByteChunk();
        if (authorizationBC.startsWithIgnoreCase("basic ", 0)) {
            authorizationBC.setOffset(authorizationBC.getOffset() + 6);
            
            byte[] decoded = Base64.decodeBase64(
                    authorizationBC.getBuffer(),
                    authorizationBC.getOffset(),
                    authorizationBC.getLength());
            
            // Get username and password
            int colon = -1;
            for (int i = 0; i < decoded.length; i++) {
                if (decoded[i] == ':') {
                    colon = i;
                    break;
                }
            }

            if (colon < 0) {
                username = new String(decoded, B2CConverter.ISO_8859_1);
            } else {
                username = new String(
                        decoded, 0, colon, B2CConverter.ISO_8859_1);
                password = new String(
                        decoded, colon + 1, decoded.length - colon - 1,
                        B2CConverter.ISO_8859_1);
            }
            
            authorizationBC.setOffset(authorizationBC.getOffset() - 6);
        }

        Principal principal = context.getRealm().authenticate(username, password);
        if (principal != null) {
            register(request, response, principal,
                    HttpServletRequest.BASIC_AUTH, username, password);
            return (true);
        }
    }
    
    StringBuilder value = new StringBuilder(16);
    value.append("Basic realm=\"");
    if (config.getRealmName() == null) {
        value.append(REALM_NAME);
    } else {
        value.append(config.getRealmName());
    }
    value.append('\"');        
    response.setHeader(AUTH_HEADER_NAME, value.toString());
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    return (false);

}
 
Example 12
Source File: MimeUtility.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
/**
 * Parse a string using the RFC 2047 rules for an "encoded-word"
 * type.  This encoding has the syntax:
 *
 * encoded-word = "=?" charset "?" encoding "?" encoded-text "?="
 *
 * @param word   The possibly encoded word value.
 *
 * @return The decoded word.
 * @throws ParseException
 * @throws UnsupportedEncodingException
 */
private static String decodeWord(String word) throws ParseException, UnsupportedEncodingException {
    // encoded words start with the characters "=?".  If this not an encoded word, we throw a
    // ParseException for the caller.

    if (!word.startsWith(ENCODED_TOKEN_MARKER)) {
        throw new ParseException("Invalid RFC 2047 encoded-word: " + word);
    }

    int charsetPos = word.indexOf('?', 2);
    if (charsetPos == -1) {
        throw new ParseException("Missing charset in RFC 2047 encoded-word: " + word);
    }

    // pull out the character set information (this is the MIME name at this point).
    String charset = word.substring(2, charsetPos).toLowerCase(Locale.ENGLISH);

    // now pull out the encoding token the same way.
    int encodingPos = word.indexOf('?', charsetPos + 1);
    if (encodingPos == -1) {
        throw new ParseException("Missing encoding in RFC 2047 encoded-word: " + word);
    }

    String encoding = word.substring(charsetPos + 1, encodingPos);

    // and finally the encoded text.
    int encodedTextPos = word.indexOf(ENCODED_TOKEN_FINISHER, encodingPos + 1);
    if (encodedTextPos == -1) {
        throw new ParseException("Missing encoded text in RFC 2047 encoded-word: " + word);
    }

    String encodedText = word.substring(encodingPos + 1, encodedTextPos);

    // seems a bit silly to encode a null string, but easy to deal with.
    if (encodedText.length() == 0) {
        return "";
    }

    try {
        // the decoder writes directly to an output stream.
        ByteArrayOutputStream out = new ByteArrayOutputStream(encodedText.length());

        byte[] decodedData;
        // Base64 encoded?
        if (encoding.equals(BASE64_ENCODING_MARKER)) {
            decodedData = Base64.decodeBase64(encodedText);
        } else if (encoding.equals(QUOTEDPRINTABLE_ENCODING_MARKER)) { // maybe quoted printable.
            byte[] encodedData = encodedText.getBytes(US_ASCII_CHARSET);
            QuotedPrintableDecoder.decode(encodedData, out);
            decodedData = out.toByteArray();
        } else {
            throw new UnsupportedEncodingException("Unknown RFC 2047 encoding: " + encoding);
        }
        // Convert decoded byte data into a string.
        return new String(decodedData, javaCharset(charset));
    } catch (IOException e) {
        throw new UnsupportedEncodingException("Invalid RFC 2047 encoding");
    }
}