org.apache.tomcat.util.codec.binary.Base64 Java Examples

The following examples show how to use org.apache.tomcat.util.codec.binary.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: AdminControllerTest.java    From semaphore-demo-java-spring with MIT License 6 votes vote down vote up
@Test
public void home() throws Exception {
    String username = "[email protected]";
    String pass = "pass123";

    User user = new User(username, encoder.encode(pass));
    doReturn(user).when(userService).loadUserByUsername(username);

    String auth = username+":"+pass;

    String token = "Basic "+ new String(Base64.encodeBase64(
            auth.getBytes(Charset.forName("US-ASCII"))));

    mockMvc.perform(
            get("/admin/home")
                    .header(HttpHeaders.AUTHORIZATION, token))
            .andExpect(
                    status().isOk());
}
 
Example #2
Source File: SignCode.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Zips the files, base 64 encodes the resulting zip and then returns the
 * string. It would be far more efficient to stream this directly to the
 * signing server but the files that need to be signed are relatively small
 * and this simpler to write.
 *
 * @param fileNames Modified names of files
 * @param files     Files to be signed
 */
private static String getApplicationString(List<String> fileNames, List<File> files)
        throws IOException {
    // 16 MB should be more than enough for Tomcat
    // TODO: Refactoring this entire class so it uses streaming rather than
    //       buffering the entire set of files in memory would make it more
    //       widely useful.
    ByteArrayOutputStream baos = new ByteArrayOutputStream(16 * 1024 * 1024);
    try (ZipOutputStream zos = new ZipOutputStream(baos)) {
        byte[] buf = new byte[32 * 1024];
        for (int i = 0; i < files.size(); i++) {
            try (FileInputStream fis = new FileInputStream(files.get(i))) {
                ZipEntry zipEntry = new ZipEntry(fileNames.get(i));
                zos.putNextEntry(zipEntry);
                int numRead;
                while ( (numRead = fis.read(buf)) >= 0) {
                    zos.write(buf, 0, numRead);
                }
            }
        }
    }

    return Base64.encodeBase64String(baos.toByteArray());
}
 
Example #3
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 #4
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 #5
Source File: WopiHostService.java    From wopihost with MIT License 6 votes vote down vote up
/**
 * Get SHA-256 value of file
 *
 * @param file
 * @return
 */
private String getHash256(File file) throws IOException, NoSuchAlgorithmException {
    String value = "";
    try (InputStream fis = new FileInputStream(file)) {
        byte[] buffer = new byte[1024];
        int numRead;
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        do {
            numRead = fis.read(buffer);
            if (numRead > 0) {
                digest.update(buffer, 0, numRead);
            }
        } while (numRead != -1);
        value = new String(Base64.encodeBase64(digest.digest()));
    }
    return value;
}
 
Example #6
Source File: OrganizationController.java    From C4SG-Obsolete with MIT License 6 votes vote down vote up
@CrossOrigin
@RequestMapping(value = "/{id}/getLogo", method = RequestMethod.GET)
@ApiOperation(value = "Retrieves organization logo")
public String retrieveOrganizationLogo(@ApiParam(value = "Organization id to get logo for", required = true)
                                     @PathVariable("id") int id) {
    File logo = new File(organizationService.getLogoUploadPath(id));
    try {
        FileInputStream fileInputStreamReader = new FileInputStream(logo);
        byte[] bytes = new byte[(int) logo.length()];
        fileInputStreamReader.read(bytes);
        return new String(Base64.encodeBase64(bytes));
    } catch (IOException e) {
        e.printStackTrace();
    return null;
}
}
 
Example #7
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 #8
Source File: AesUtil.java    From springboot-learn with MIT License 6 votes vote down vote up
/**
 * AES加密
 *
 * @param passwd  加密的密钥
 * @param content 需要加密的字符串
 * @return 返回Base64转码后的加密数据
 * @throws Exception
 */
public static String encrypt(String passwd, String content) throws Exception {
    // 创建密码器
    Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);

    byte[] byteContent = content.getBytes("utf-8");

    // 初始化为加密模式的密码器
    cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(passwd));

    // 加密
    byte[] result = cipher.doFinal(byteContent);

    //通过Base64转码返回
    return Base64.encodeBase64String(result);
}
 
Example #9
Source File: TestSSOnonLoginAndBasicAuthenticator.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
private BasicCredentials(String aMethod,
        String aUsername, String aPassword) {
    method = aMethod;
    username = aUsername;
    password = aPassword;
    String userCredentials = username + ":" + password;
    byte[] credentialsBytes =
            userCredentials.getBytes(B2CConverter.ISO_8859_1);
    String base64auth = Base64.encodeBase64String(credentialsBytes);
    credentials= method + " " + base64auth;
}
 
Example #10
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 #11
Source File: TestNonLoginAndBasicAuthenticator.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
private BasicCredentials(String aMethod,
        String aUsername, String aPassword) {
    method = aMethod;
    username = aUsername;
    password = aPassword;
    String userCredentials = username + ":" + password;
    byte[] credentialsBytes =
            userCredentials.getBytes(B2CConverter.ISO_8859_1);
    String base64auth = Base64.encodeBase64String(credentialsBytes);
    credentials= method + " " + base64auth;
}
 
Example #12
Source File: TestRestCsrfPreventionFilter2.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
private BasicCredentials(String aMethod, String aUsername, String aPassword) {
    method = aMethod;
    username = aUsername;
    password = aPassword;
    String userCredentials = username + ":" + password;
    byte[] credentialsBytes = userCredentials.getBytes(B2CConverter.ISO_8859_1);
    String base64auth = Base64.encodeBase64String(credentialsBytes);
    credentials = method + " " + base64auth;
}
 
Example #13
Source File: Test001Records.java    From java-crud-api with MIT License 5 votes vote down vote up
@Test
public void test035EditCategoryWithBinaryContent() throws Exception {
	String string = "€ \000abc\000\n\r\\b\000";
	String binary = Base64.encodeBase64String(string.getBytes("UTF-8"));
	String b64url = Base64.encodeBase64URLSafeString(string.getBytes("UTF-8"));
	mockMvc.perform(
			put("/records/categories/2").contentType("application/json").content("{\"icon\":\"" + b64url + "\"}"))
			.andExpect(status().isOk()).andExpect(content().string("1"));
	mockMvc.perform(get("/records/categories/2")).andExpect(status().isOk())
			.andExpect(content().string("{\"id\":2,\"name\":\"article\",\"icon\":\"" + binary + "\"}"));
}
 
Example #14
Source File: Test001Records.java    From java-crud-api with MIT License 5 votes vote down vote up
@Test
public void test037EditCategoryWithBinaryContentWithPost() throws Exception {
	String string = "€ \000abc\000\n\r\\b\000";
	String binary = Base64.encodeBase64String(string.getBytes("UTF-8"));
	String b64url = Base64.encodeBase64URLSafeString(string.getBytes("UTF-8"));
	mockMvc.perform(
			put("/records/categories/2").contentType("application/x-www-form-urlencoded").content("icon=" + b64url))
			.andExpect(status().isOk()).andExpect(content().string("1"));
	mockMvc.perform(get("/records/categories/2")).andExpect(status().isOk())
			.andExpect(content().string("{\"id\":2,\"name\":\"article\",\"icon\":\"" + binary + "\"}"));
}
 
Example #15
Source File: HttpHelper.java    From OAuth2-Java with Apache License 2.0 5 votes vote down vote up
public HttpPost addHeader(HttpPost post) {
	String base64ClientIdSec = Base64.encodeBase64String((oAuth2Configuration.getAppClientId() + ":" + oAuth2Configuration.getAppClientSecret()).getBytes());
       post.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
       post.setHeader("Authorization", "Basic " + base64ClientIdSec);
       post.setHeader("Accept", "application/json");
       return post;
}
 
Example #16
Source File: Key.java    From cms with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws Exception {


    FileInputStream is = new FileInputStream(new File("jwt.jks"));

    KeyStore keyStore = KeyStore.getInstance("JKS");
    //这里填设置的keystore密码,两个可以不一致
    keyStore.load(is, "123qwe".toCharArray());

    //加载别名,这里认为只有一个别名,可以这么取;当有多个别名时,别名要用参数传进来。不然,第二次的会覆盖第一次的
    Enumeration aliasEnum = keyStore.aliases();
    String keyAlias = "jwt";
    while (aliasEnum.hasMoreElements()) {
        keyAlias = (String) aliasEnum.nextElement();
        System.out.println("别名" + keyAlias);
    }

    Certificate certificate = keyStore.getCertificate(keyAlias);

    //加载公钥
    PublicKey publicKey = keyStore.getCertificate(keyAlias).getPublicKey();
    //加载私钥,这里填私钥密码
    PrivateKey privateKey = ((KeyStore.PrivateKeyEntry) keyStore.getEntry(keyAlias,
            new KeyStore.PasswordProtection("123qwe".toCharArray()))).getPrivateKey();

    //加载私钥另一写法
    //PrivateKey privateKey = (PrivateKey) keyStore.getKey(keyAlias, "123456".toCharArray());

    //base64输出私钥
    String strKey = Base64.encodeBase64String(privateKey.getEncoded());
    System.out.println(strKey);

    //测试签名
    String sign = Base64.encodeBase64String(sign("测试msg".getBytes(), privateKey, "SHA1withRSA", null));
    //测试验签
    boolean verfi = verify("测试msg".getBytes(), Base64.decodeBase64(sign), publicKey, "SHA1withRSA", null);
    System.out.println(verfi);

}
 
Example #17
Source File: DesUtil.java    From javabase with Apache License 2.0 5 votes vote down vote up
/**
 * 带向量的加密
 * @param str
 * @param secretKey
 * @param iv
 * @return
    * @throws Exception
    */
public static String encrypt(String str, String secretKey, byte[] iv) throws Exception {
	IvParameterSpec zeroIv = new IvParameterSpec(iv);
	SecretKeySpec key = new SecretKeySpec(secretKey.getBytes("UTF-8"), "DES");
	Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
	cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
	byte[] encryptedData = cipher.doFinal(str.getBytes("UTF-8"));
	byte[] temp = Base64.encodeBase64(encryptedData, false);
	return new String(temp);
}
 
Example #18
Source File: TestSSOnonLoginAndBasicAuthenticator.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
private BasicCredentials(String aMethod,
        String aUsername, String aPassword) {
    method = aMethod;
    username = aUsername;
    password = aPassword;
    String userCredentials = username + ":" + password;
    byte[] credentialsBytes =
            userCredentials.getBytes(B2CConverter.ISO_8859_1);
    String base64auth = Base64.encodeBase64String(credentialsBytes);
    credentials= method + " " + base64auth;
}
 
Example #19
Source File: TestNonLoginAndBasicAuthenticator.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
private BasicCredentials(String aMethod,
        String aUsername, String aPassword) {
    method = aMethod;
    username = aUsername;
    password = aPassword;
    String userCredentials = username + ":" + password;
    byte[] credentialsBytes =
            userCredentials.getBytes(B2CConverter.ISO_8859_1);
    String base64auth = Base64.encodeBase64String(credentialsBytes);
    credentials= method + " " + base64auth;
}
 
Example #20
Source File: TestRestCsrfPreventionFilter2.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
private BasicCredentials(String aMethod, String aUsername, String aPassword) {
    method = aMethod;
    username = aUsername;
    password = aPassword;
    String userCredentials = username + ":" + password;
    byte[] credentialsBytes = userCredentials.getBytes(B2CConverter.ISO_8859_1);
    String base64auth = Base64.encodeBase64String(credentialsBytes);
    credentials = method + " " + base64auth;
}
 
Example #21
Source File: AESUtils.java    From CoolSignIn with Apache License 2.0 5 votes vote down vote up
public static String encrypt(int target) {
	target += PADDING;
	String targetString = Integer.toString(target);
	targetString += STRINGPADDING;
	try {
		return new String(Base64.encodeBase64(encrypt(targetString,
				encryptionKey)));

	} catch (Exception e) {
		e.printStackTrace();
		return null;
	}
}
 
Example #22
Source File: TestAuthInfoResponseHeaders.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private BasicCredentials(String aMethod,
        String aUsername, String aPassword) {
    method = aMethod;
    username = aUsername;
    password = aPassword;
    String userCredentials = username + ":" + password;
    byte[] credentialsBytes =
            userCredentials.getBytes(StandardCharsets.ISO_8859_1);
    String base64auth = Base64.encodeBase64String(credentialsBytes);
    credentials= method + " " + base64auth;
}
 
Example #23
Source File: BasicAuthenticator.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public String getAuthorization(String requestUri, String WWWAuthenticate,
        Map<String, Object> userProperties) throws AuthenticationException {

    String userName = (String) userProperties.get(Constants.WS_AUTHENTICATION_USER_NAME);
    String password = (String) userProperties.get(Constants.WS_AUTHENTICATION_PASSWORD);

    if (userName == null || password == null) {
        throw new AuthenticationException(
                "Failed to perform Basic authentication due to  missing user/password");
    }

    Map<String, String> wwwAuthenticate = parseWWWAuthenticateHeader(WWWAuthenticate);

    String userPass = userName + ":" + password;
    Charset charset;

    if (wwwAuthenticate.get(charsetparam) != null
            && wwwAuthenticate.get(charsetparam).equalsIgnoreCase("UTF-8")) {
        charset = StandardCharsets.UTF_8;
    } else {
        charset = StandardCharsets.ISO_8859_1;
    }

    String base64 = Base64.encodeBase64String(userPass.getBytes(charset));

    return " Basic " + base64;
}
 
Example #24
Source File: TestSSOnonLoginAndBasicAuthenticator.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private BasicCredentials(String aMethod,
        String aUsername, String aPassword) {
    method = aMethod;
    username = aUsername;
    password = aPassword;
    String userCredentials = username + ":" + password;
    byte[] credentialsBytes =
            userCredentials.getBytes(StandardCharsets.ISO_8859_1);
    String base64auth = Base64.encodeBase64String(credentialsBytes);
    credentials= method + " " + base64auth;
}
 
Example #25
Source File: TestNonLoginAndBasicAuthenticator.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private BasicCredentials(String aMethod,
        String aUsername, String aPassword) {
    method = aMethod;
    username = aUsername;
    password = aPassword;
    String userCredentials = username + ":" + password;
    byte[] credentialsBytes =
            userCredentials.getBytes(StandardCharsets.ISO_8859_1);
    String base64auth = Base64.encodeBase64String(credentialsBytes);
    credentials= method + " " + base64auth;
}
 
Example #26
Source File: TestBasicAuthParser.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private BasicAuthHeader(String method, String username,
        String password, String extraBlob) {
    prefix(method);

    String userCredentials =
            ((password == null) || (password.length() < 1))
            ? username
            : username + ":" + password;
    byte[] credentialsBytes =
            userCredentials.getBytes(StandardCharsets.ISO_8859_1);
    String base64auth = Base64.encodeBase64String(credentialsBytes);
    byte[] base64Bytes =
            base64auth.getBytes(StandardCharsets.ISO_8859_1);

    byte[] extraBytes =
            ((extraBlob == null) || (extraBlob.length() < 1))
            ? null :
            extraBlob.getBytes(StandardCharsets.ISO_8859_1);

    try {
        authHeader.append(base64Bytes, 0, base64Bytes.length);
        if (extraBytes != null) {
            authHeader.append(extraBytes, 0, extraBytes.length);
        }
    }
    catch (IOException ioe) {
        throw new IllegalStateException("unable to extend ByteChunk:"
                + ioe.getMessage());
    }
    // emulate tomcat server - offset points to method in header
    authHeader.setOffset(initialOffset);
}
 
Example #27
Source File: TestRestCsrfPreventionFilter2.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private BasicCredentials(String aMethod, String aUsername, String aPassword) {
    method = aMethod;
    username = aUsername;
    password = aPassword;
    String userCredentials = username + ":" + password;
    byte[] credentialsBytes = userCredentials.getBytes(StandardCharsets.ISO_8859_1);
    String base64auth = Base64.encodeBase64String(credentialsBytes);
    credentials = method + " " + base64auth;
}
 
Example #28
Source File: AesUtil.java    From springboot-learn with MIT License 5 votes vote down vote up
/**
 * AES解密
 *
 * @param passwd    加密的密钥
 * @param encrypted 已加密的密文
 * @return 返回解密后的数据
 * @throws Exception
 */
public static String decrypt(String passwd, String encrypted) throws Exception {
    //实例化
    Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);

    //使用密钥初始化,设置为解密模式
    cipher.init(Cipher.DECRYPT_MODE, getSecretKey(passwd));

    //执行操作
    byte[] result = cipher.doFinal(Base64.decodeBase64(encrypted));

    return new String(result, "utf-8");
}
 
Example #29
Source File: AesUtil.java    From base-admin with MIT License 5 votes vote down vote up
/**
 * 加密
 *
 * @param content    加密的字符串
 * @param encryptKey key值
 */
public static String encrypt(String content, String encryptKey) throws Exception {
    //设置Cipher对象
    Cipher cipher = Cipher.getInstance(ALGORITHMS, PROVIDER);
    cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), KEY_ALGORITHM));

    //调用doFinal
    // 转base64
    return Base64.encodeBase64String(cipher.doFinal(content.getBytes(StandardCharsets.UTF_8)));

}
 
Example #30
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));
}