/** * 加密 * @param datasource byte[] * @param password String * @return byte[] */ public static String encrypt(String datasource, String password) { try { if(StringUtils.trimToNull(datasource) == null){ return null; } SecureRandom random = new SecureRandom(); DESKeySpec desKey = new DESKeySpec(password.getBytes()); // 创建一个密匙工厂,然后用它把DESKeySpec转换成 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey securekey = keyFactory.generateSecret(desKey); // Cipher对象实际完成加密操作 Cipher cipher = Cipher.getInstance("DES"); // 用密匙初始化Cipher对象 cipher.init(Cipher.ENCRYPT_MODE, securekey, random); // 现在,获取数据并加密 // 正式执行加密操作 return new BASE64Encoder().encode(cipher.doFinal(datasource.getBytes())); } catch (Throwable e) { e.printStackTrace(); } return null; }
private static String EncryptId(String id) { byte[] byte1 = "3go8&$8*3*3h0k(2)2".getBytes(); byte[] byte2 = id.getBytes(); int byte1Length = byte1.length; for (int i = 0; i < byte2.length; i++) { byte tmp = byte1[(i % byte1Length)]; byte2[i] = ((byte) (byte2[i] ^ tmp)); } MessageDigest md5; try { md5 = MessageDigest.getInstance("MD5"); } catch (Exception e) { e.printStackTrace(); return ""; } byte[] md5Bytes = md5.digest(byte2); String retval = new BASE64Encoder().encode(md5Bytes); retval = retval.replace('/', '_'); retval = retval.replace('+', '-'); return retval; }
/** * <pre> * 图片文件转化为Base64编码字符串 * * </pre> * * @param image * @param type * @return */ public static String encodeToString(BufferedImage image, String type) { String imageString = null; ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { ImageIO.write(image, type, bos); byte[] imageBytes = bos.toByteArray(); BASE64Encoder encoder = new BASE64Encoder(); imageString = encoder.encode(imageBytes); bos.close(); } catch (IOException e) { throw new RuntimeException(e); } return imageString.replaceAll("\\n", ""); }
private String getAppData(){ activeUser = CDI.current().select(ActiveUser.class).get(); CharSequence http = "http://"; CharSequence https = "https://"; AppContext appContext = CDI.current().select(AppContext.class).get(); Gson gson = new Gson(); Map map = new HashMap(); map.put("base_url", requestContext.getBaseURL()); map.put("base64_url", new BASE64Encoder().encode(requestContext.getBaseURL().getBytes())); map.put("simple_base_url", requestContext.getBaseURL().replace(http,"").replace(https,"")); map.put("deployId",appContext.getDeployId()); map.put("deployMode",appContext.getDeployMode().toString()); map.put("csrfToken",activeUser.getCsrfToken()); return gson.toJson(map); }
public String generateTokeCode(){ String value = System.currentTimeMillis()+new Random().nextInt()+""; //获取数据指纹,指纹是唯一的 try { MessageDigest md = MessageDigest.getInstance("md5"); byte[] b = md.digest(value.getBytes());//产生数据的指纹 //Base64编码 BASE64Encoder be = new BASE64Encoder(); be.encode(b); return be.encode(b);//制定一个编码 } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; }
public static String getBase64(String str) { byte[] b = null; String s = null; try { b = str.getBytes("utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } if (b != null) { s = new BASE64Encoder().encode(b); } return s; }
/** * Creates a {@link SignedJarBuilder} with a given output stream, and signing information. * <p/>If either <code>key</code> or <code>certificate</code> is <code>null</code> then * the archive will not be signed. * * @param out the {@link OutputStream} where to write the Jar archive. * @param key the {@link PrivateKey} used to sign the archive, or <code>null</code>. * @param certificate the {@link X509Certificate} used to sign the archive, or * <code>null</code>. * @throws IOException * @throws NoSuchAlgorithmException */ public SignedJarBuilder(OutputStream out, PrivateKey key, X509Certificate certificate) throws IOException, NoSuchAlgorithmException { mOutputJar = new JarOutputStream(new BufferedOutputStream(out)); mOutputJar.setLevel(9); mKey = key; mCertificate = certificate; if (mKey != null && mCertificate != null) { mManifest = new Manifest(); Attributes main = mManifest.getMainAttributes(); main.putValue("Manifest-Version", "1.0"); main.putValue("Created-By", "1.0 (ApkPatch)"); mBase64Encoder = new BASE64Encoder(); mMessageDigest = MessageDigest.getInstance(DIGEST_ALGORITHM); } }
public static String createSecureToken(String token, String id, String sharedSecret, String data, long curTime) throws IOException { if( id == null ) { id = ""; } String time = Long.toString(curTime); String toMd5 = token + id + time + sharedSecret; StringBuilder b = new StringBuilder(); b.append(URLEncoder.encode(token, "UTF-8")); b.append(':'); b.append(URLEncoder.encode(id, "UTF-8")); b.append(':'); b.append(time); b.append(':'); b.append(new BASE64Encoder().encode(getMd5Bytes(toMd5))); if( data != null && data.length() > 0 ) { b.append(':'); b.append(data); } return b.toString(); }
/** * Creates a {@link SignedJarBuilder} with a given output stream, and signing information. * <p/>If either <code>key</code> or <code>certificate</code> is <code>null</code> then * the archive will not be signed. * @param out the {@link OutputStream} where to write the Jar archive. * @param key the {@link PrivateKey} used to sign the archive, or <code>null</code>. * @param certificate the {@link X509Certificate} used to sign the archive, or * <code>null</code>. * @throws IOException * @throws NoSuchAlgorithmException */ public SignedJarBuilder(OutputStream out, PrivateKey key, X509Certificate certificate) throws IOException, NoSuchAlgorithmException { mOutputJar = new JarOutputStream(new BufferedOutputStream(out)); mOutputJar.setLevel(9); mKey = key; mCertificate = certificate; if (mKey != null && mCertificate != null) { mManifest = new Manifest(); Attributes main = mManifest.getMainAttributes(); main.putValue("Manifest-Version", "1.0"); main.putValue("Created-By", "1.0 (Android)"); mBase64Encoder = new BASE64Encoder(); mMessageDigest = MessageDigest.getInstance(DIGEST_ALGORITHM); } }
/** * 将图片文件转化为字节数组字符串,并对其进行Base64编码处理 * @param imgSrcPath 生成64编码的图片的路径 * @return * @throws UnsupportedEncodingException */ public static String getImageStr(String imgSrcPath) throws UnsupportedEncodingException{ InputStream in = null; byte[] data = null; //读取图片字节数组 try { in = new FileInputStream(imgSrcPath); data = new byte[in.available()]; in.read(data); in.close(); } catch (IOException e) { e.printStackTrace(); } //对字节数组Base64编码 BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(data); }
public static String encodeBase64(String str) { if (str == null) { return null; } byte[] b; String s = null; try { b = str.getBytes("UTF-8"); } catch (Exception e) { return null; } if (b != null) { s = new BASE64Encoder().encode(b); } return s; }
public static String getData(String address) { StringBuffer buffer = new StringBuffer(); try { URL url = new URL(address); URLConnection con = url.openConnection(); byte[] encodedPassword = "doof:letmein2011".getBytes(); BASE64Encoder encoder = new BASE64Encoder(); con.setRequestProperty("Authorization", "Basic " + encoder.encode(encodedPassword)); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { buffer.append(inputLine + "\n"); } in.close(); } catch (Exception ex) { ex.printStackTrace(); } return buffer.toString(); }
/** * 将图片文件转化为字节数组字符串,并对其进行Base64编码处理 * @param path 图片路径 * @return */ public static String covertImageToBase64(String path) { byte [] buf = null; // 读取图片字节数组 try { InputStream in = new FileInputStream(path); buf = new byte[in.available()]; in.read(buf); in.close(); }catch(IOException e) { e.printStackTrace(); } // 对字节数组进行Base64编码 BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(buf); // 返回Base64编码字符串 }
public static String encriptar(String passPhrase, String str) throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException { Cipher ecipher = null; Cipher dcipher = null; java.security.spec.KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), SALT_BYTES, ITERATION_COUNT); SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec); ecipher = Cipher.getInstance(key.getAlgorithm()); dcipher = Cipher.getInstance(key.getAlgorithm()); java.security.spec.AlgorithmParameterSpec paramSpec = new PBEParameterSpec(SALT_BYTES, ITERATION_COUNT); ecipher.init(1, key, paramSpec); dcipher.init(2, key, paramSpec); byte utf8[] = str.getBytes("UTF8"); byte enc[] = ecipher.doFinal(utf8); return (new BASE64Encoder()).encode(enc); }
/** * 二维码生成 ,储存地址qrcodeFilePath * * @param text 二维码内容 * @return Base64Code String */ @SuppressWarnings("restriction") public String createQrcode(String text){ String Imgencode=""; byte[] imageByte=null; String formatName="PNG"; try { // int qrcodeWidth = 300; int qrcodeHeight = 300; HashMap<EncodeHintType, String> hints = new HashMap<EncodeHintType, String>(); hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, qrcodeWidth, qrcodeHeight, hints); ByteArrayOutputStream out = new ByteArrayOutputStream(); BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix); ImageIO.write(bufferedImage, formatName, out); imageByte=out.toByteArray(); Imgencode = new sun.misc.BASE64Encoder().encode(imageByte); } catch (Exception e) { e.printStackTrace(); } return Imgencode; }
public AESEncryptor() { try { /* Derive the key, given password and salt. */ SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); KeySpec spec; spec = new PBEKeySpec(Constants.FRAMEWORK_NAME.toCharArray(), SALT, ITERATIONS, KEY_SIZE); SecretKey tmp = factory.generateSecret(spec); secret = new SecretKeySpec(tmp.getEncoded(), "AES"); // CBC = Cipher Block chaining // PKCS5Padding Indicates that the keys are padded cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); // For production use commons base64 encoder base64Encoder = new BASE64Encoder(); } catch (Exception e) { throw new RuntimeException("Unable to initialize", e); } }
public static String getImageBase64(BufferedImage img) { InputStream in = null; byte[] data = null; try { ByteArrayOutputStream bs = new ByteArrayOutputStream(); ImageOutputStream imOut = ImageIO.createImageOutputStream(bs); ImageIO.write(img, "jpg",imOut); in = new ByteArrayInputStream(bs.toByteArray()); data = new byte[in.available()]; in.read(data); in.close(); imOut.close(); } catch (IOException e) { e.printStackTrace(); } BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(data); }
/** * Base64加密 * @param str * @return */ public static String getBase64(String str) { byte[] b = null; String s = null; try { b = str.getBytes("utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } if (b != null) { s = new BASE64Encoder().encode(b); } return s; }
/** * Dump the certificate base64 encoded. * * @param sb write certificate here * @param certificate the certificate * @return StringBuilder */ public StringBuilder dumpCert(StringBuilder sb, Certificate certificate ) throws CertificateException { final BASE64Encoder base64encoder = new BASE64Encoder(); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final PrintStream ps = new PrintStream(baos); try { ps.println(); base64encoder.encodeBuffer(certificate.getEncoded(), ps); // ps.flush(); // baos.flush(); } catch (IOException ioex) { throw new CertificateException( "Cannot dump certificate", ioex ); } finally { try { baos.close(); } catch (IOException ex) { // ignore it } } sb.append( NbBundle.getMessage( KeyStoreFormatter.class, "dumpCert", baos.toString() ) ); return sb; }
public static String getPrivate(String path,String pwd){ try { KeyStore ks= KeyStore.getInstance("PKCS12"); FileInputStream is=new FileInputStream(path); ks.load(is,pwd.toCharArray()); is.close(); System.out.println("keystore type=" + ks.getType()); Enumeration enuma = ks.aliases(); String keyAlias = null; if (enuma.hasMoreElements()){ keyAlias = (String)enuma.nextElement(); System.out.println("alias=[" + keyAlias + "]"); } System.out.println("is key entry=" + ks.isKeyEntry(keyAlias)); BASE64Encoder enc=new BASE64Encoder(); PrivateKey privatekey = (PrivateKey) ks.getKey(keyAlias, pwd.toCharArray()); System.out.println("private key = " + enc.encode(privatekey.getEncoded())); return enc.encode(privatekey.getEncoded()); } catch (Exception e) { e.printStackTrace(); return null; } }
private String createCustomCookieValue() { String value = null; byte[] buffer = null; MessageDigest md = null; BASE64Encoder encoder = new BASE64Encoder(); try { md = MessageDigest.getInstance("SHA"); buffer = new Date().toString().getBytes(); md.update(buffer); value = encoder.encode(md.digest()); original = value; } catch (Exception e) { e.printStackTrace(); } return value; }
/** * 将生成的二维码图片转化为base64编码,直接传给浏览器显示 * 好处是可以传图片的同时将参数也一并传递过去 * @param content * @param width * @param height * @return */ public static String toBase64(String content,int width,int height){ String qrCodeBASE64 = null; try{ BitMatrix bitMatrix = new MultiFormatWriter().encode(content,BarcodeFormat.QR_CODE , width, height); BufferedImage bufferedImage = QRCodeUtil.toBufferedImage(bitMatrix); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ImageIO.write(bufferedImage,"png",byteArrayOutputStream); byte[] data = byteArrayOutputStream.toByteArray(); byteArrayOutputStream.flush(); byteArrayOutputStream.close(); BASE64Encoder base64 = new BASE64Encoder(); qrCodeBASE64 = base64.encode(data); }catch(Exception e){ e.printStackTrace(); } return qrCodeBASE64; }
public void updatePlayer(Player player) { try { PreparedStatement prep = connection.prepareStatement("UPDATE players SET username = ?, email = ?, passwordHash = ?, passwordSalt = ?" + "WHERE playerID = ?"); prep.setString(1, player.getUsername()); prep.setString(2, player.getEmail()); BASE64Encoder enc = new BASE64Encoder(); String hash = enc.encode(player.getPasswordHash()); String salt = enc.encode(player.getPasswordSalt()); prep.setString(3, hash); prep.setString(4, salt); prep.setInt(5, player.getId()); prep.execute(); } catch (SQLException e) { e.printStackTrace(); } }
public static void writeCiphersToDisk(byte[][] ciphers, String filePath) { try { String[] encodedCiphers = new String[ciphers.length]; BASE64Encoder encoder = new BASE64Encoder(); for (int i = 0; i < ciphers.length; i++) encodedCiphers[i] = encoder.encode(ciphers[i]); File f = new File(filePath); FileOutputStream fos = new FileOutputStream(f); BufferedOutputStream bos = new BufferedOutputStream(fos); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(encodedCiphers); oos.flush(); oos.close(); } catch (Exception e) { e.printStackTrace(); } }
@Test(description = "This test case tests Signature verification of a Certificate against the keystore") public void testVerifySignature() throws KeystoreException, CertificateEncodingException, CMSException, IOException { BASE64Encoder encoder = new BASE64Encoder(); //generate and save a certificate in the keystore X509Certificate x509Certificate = managementService.generateX509Certificate(); //Generate CMSdata CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); List<X509Certificate> list = new ArrayList<>(); list.add(x509Certificate); JcaCertStore store = new JcaCertStore(list); generator.addCertificates(store); CMSSignedData degenerateSd = generator.generate(new CMSAbsentContent()); byte[] signature = degenerateSd.getEncoded(); boolean verifySignature = managementService.verifySignature(encoder.encode(signature)); Assert.assertNotNull(verifySignature); Assert.assertTrue(verifySignature); log.info("VerifySignature Test Successful"); }
@Test(description = "This test case tests extracting Certificate from the header Signature") public void testExtractCertificateFromSignature() throws KeystoreException, CertificateEncodingException, CMSException, IOException { BASE64Encoder encoder = new BASE64Encoder(); //generate and save a certificate in the keystore X509Certificate x509Certificate = managementService.generateX509Certificate(); //Generate CMSdata CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); List<X509Certificate> list = new ArrayList<>(); list.add(x509Certificate); JcaCertStore store = new JcaCertStore(list); generator.addCertificates(store); CMSSignedData degenerateSd = generator.generate(new CMSAbsentContent()); byte[] signature = degenerateSd.getEncoded(); X509Certificate certificate = managementService.extractCertificateFromSignature(encoder.encode(signature)); Assert.assertNotNull(certificate); Assert.assertEquals(certificate.getType(), CertificateManagementConstants.X_509); log.info("ExtractCertificateFromSignature Test Successful"); }
private int verifySignature(Boolean algSha256, String envelope, String filename) throws Exception { MessageDigest hashSum = null; if(algSha256){ hashSum = MessageDigest.getInstance("SHA-256"); } else { hashSum = MessageDigest.getInstance("SHA-1"); } hashSum.update(Convert.readFile(filename)); byte[] digestResult = hashSum.digest(); String digestB64 = (new BASE64Encoder()).encode(digestResult); String envelopeRebuilt = rebuilder.rebuildEnvelope(0, envelope); int validateSign = serv.validateSignWithStatus(envelopeRebuilt, digestB64, null, false); return validateSign; }
private String composeEnvelopeADRB21(byte[] sign, byte[] x509, byte[] origHash, Date signingTime) throws Exception { X509Certificate cert = loadCert(x509); byte[] ret = ccServ .composeBodySha256(sign, cert, origHash, signingTime); byte[] hashSa = ccServ.hashSignedAttribSha256(origHash, signingTime, cert); if (!verifySign(NDX_SHA256, cert, ccServ.calcSha256(hashSa), sign)) { throw new InvalidSigntureException(); } BASE64Encoder b64enc = new BASE64Encoder(); return b64enc.encode(ret); }
private String composeEnvelopeADRB10(byte[] sign, byte[] x509, byte[] origHash, Date signingTime) throws Exception { X509Certificate cert = loadCert(x509); byte[] ret = ccServ.composeBodySha1(sign, cert, origHash, signingTime); byte[] hashSa = ccServ .hashSignedAttribSha1(origHash, signingTime, cert); if (!verifySign(NDX_SHA1, cert, ccServ.calcSha1(hashSa), sign)) { throw new InvalidSigntureException(); } BASE64Encoder b64enc = new BASE64Encoder(); return b64enc.encode(ret); }
/** * 加密String明文输入,String密文输出 * * @param strMing * @return */ public String getEncString(String strMing) { byte[] byteMi = null; byte[] byteMing = null; String strMi = ""; BASE64Encoder base64en = new BASE64Encoder(); try { byteMing = strMing.getBytes("UTF8"); byteMi = getEncCode(byteMing); strMi = base64en.encode(byteMi); } catch (Exception e) { e.printStackTrace(); } finally { base64en = null; byteMing = null; byteMi = null; } return strMi; }
public String generateToken(){//���ݵ�ǰʱ�����ֵ�Լ�һ����������õ�һ��Ψһ������� String token=System.currentTimeMillis()+new Random().nextInt()+""; //�������������һ�£���Ҫ��������ָ��/ժҪ���̶�128λ try {//�������128λ����ժҪ��һ�㲽�� MessageDigest md=MessageDigest.getInstance("md5"); byte[] md5=md.digest(token.getBytes()); //Ϊ�˷�ֱֹ�ӹ���string���ص��������������봮����Ҫ����base64���룬����md5�����е�ÿ�����ֽ�ת�����ĸ��ֽڣ������������ֽڱ��浽�ĸ��ֽ��� //��ô�ĸ��ֽڵ�ÿ���ֽڱ���ԭ�������ֽڵ�6λ����ÿ�����ֽ�תΪ�ĸ��ֽ�֮�����ĸ��ֽڵ����ݵ��ص��ǣ�ÿ���ֽڵ���Чλֻ�Ǻ���λ��ǰ��λ���㣬��ôÿ���ֽڵ� //��Χ��00000000--00111111��0~63��,��ôһת�룬��ô�ĸ��ֽڵ�ÿ���ֽڶ�Ӧ���ַ�����������Ϥ�Ŀɼ����ַ� BASE64Encoder encoder=new BASE64Encoder(); return encoder.encode(md5); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } }
private String dataStringify(ResultSet rs) throws IOException, SQLException { ResultSetMetaData rsmd = rs.getMetaData(); rs.last(); int columnNumber = rsmd.getColumnCount(), rowsNumber = rs.getRow(), currentRow = 0; StringBuilder[] stb = new StringBuilder[rowsNumber]; rs.first(); //Move through the resultset... for (int rsRow = 1; rsRow <= rowsNumber; rsRow++) { stb[currentRow] = new StringBuilder(); for (int i = 1; i <= columnNumber; i++) { //todo: handle types here. Object obj = rs.getObject(i); stb[currentRow].append(((obj instanceof byte[]) ? (new BASE64Encoder().encode((byte[]) obj)).replaceAll("\n|\r", "") : obj.toString())); stb[currentRow].append((columnNumber == i ? "" : columnsSeparator)); } currentRow++; rs.next(); } return String.join(rowsSeparator, stb); }
/** * 加密 * * @param password 需要加密的字符串 */ private static String digestPassword(String password) { try { SecureRandom random = new SecureRandom(); byte[] salt = new byte[EncodeKit.SALT_SIZE]; random.nextBytes(salt); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(salt); md.update(password.getBytes()); byte[] digest = md.digest(); BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(salt) + encoder.encode(digest); } catch (NoSuchAlgorithmException ne) { System.err.println(ne.toString()); return null; } catch (Exception e) { System.err.println(e.toString()); return null; } }
public BancoSeguroBasicAuthenticator(X509Certificate cert, KeyPair keys) throws Exception { /* username recebe o conteudo do certificado, * em formato Base64 */ this.username = CertificadoSerializador.certToStr(cert); /* password recebe a assinatura do conteudo do certificado, * em formato Base64 */ this.password = new BASE64Encoder().encode( CertificadoAssinador.sign(keys.getPrivate(), cert.getEncoded())) .replaceAll("\\s+",""); if (trace) { logger.trace( String.format("BancoSeguro Basic Authenticator: uname=%s", this.username)); logger.trace( String.format("BancoSeguro Basic Authenticator: pass=%s", this.password)); } }
public SICidBasicAuthenticator(X509Certificate cert, KeyPair keys) throws Exception { /* username recebe o conteudo do certificado, * em formato Base64 */ this.username = CertificadoSerializador.certToStr(cert); /* password recebe a assinatura do conteudo do certificado, * em formato Base64 */ this.password = new BASE64Encoder().encode( CertificadoAssinador.sign(keys.getPrivate(), cert.getEncoded())) .replaceAll("\\s+",""); if (trace) { logger.trace( String.format("SICid Basic Authenticator: uname=%s", this.username)); logger.trace( String.format("SICid Basic Authenticator: pass=%s", this.password)); } }
public static String encodeToString(BufferedImage image, String type) { String imageString = null; ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { ImageIO.write(image, type, bos); byte[] imageBytes = bos.toByteArray(); BASE64Encoder encoder = new BASE64Encoder(); imageString = encoder.encode(imageBytes); bos.close(); } catch (IOException e) { e.printStackTrace(); } return imageString; }