How to convert com.hierynomus.sbmj.share.File to Base64 String? - base64

Using Java 1.8 and SMBJ 0.11.5
Trying to read file from Network share using..
File remoteFile = networkShare.openFile(..);
https://www.javadoc.io/doc/com.hierynomus/smbj/latest/com/hierynomus/smbj/share/DiskShare.html#openFile(java.lang.String,java.util.Set,java.util.Set,java.util.Set,com.hierynomus.mssmb2.SMB2CreateDisposition,java.util.Set)
com.hierynomus.sbmj.share.File (from network share folder) to Base64 String?

Used apache.commons.io library
java.io.InputStream is = smbFileDownload.getInputStream(); byte[] bytes1 = IOUtils.toByteArray(is); byte[] byte64 = Base64.getEncoder().encode(bytes1); String bass64Str = (new String(byte64));

Related

Error trying to attach an image to an Azure DevOps wiki page

I have successfully used the Azure DevOps API to create multiple wiki pages, via a standalone C# desktop app. Now I'm trying to attach an image (currently stored locally) to the wiki (as per https://learn.microsoft.com/en-us/rest/api/azure/devops/wiki/attachments/create?view=azure-devops-rest-6.0), but get an error
The wiki attachment creation failed with message : The input is not a
valid Base-64 string as it contains a non-base 64 character, more than
two padding characters, or an illegal character among the padding
characters.
This is the code that I use to read the image file and convert it to a Base64 string - is this correct?
string base64String = null;
string img = File.ReadAllText(att.Value);
byte[] byteCredentials = UTF8Encoding.UTF8.GetBytes(img);
base64String= Convert.ToBase64String(byteCredentials);
Then I create the "content" for the API call as
string data = #"{""content"": """ + base64String + #"""}";
and run the API call
string url = "https://dev.azure.com/{organization}/{project}/_apis/wiki/wikis/{wikiIdentifier}/attachments?name=Image.png&api-version=6.0";
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.ContentType = "application/octet-stream";
request.Method = "PUT";
request.Proxy.Credentials = CredentialCache.DefaultCredentials;
request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{1}", "AzurePAT"))));
if (data != null)
{
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(data);
}
}
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
string result = string.Empty;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}
Can anyone see anything wrong with any of this? The concept of setting up a "content" JSON with an encoded Base64 string doesn't seem to be documented, so have I done it correctly?
Any help or advice gladly appreciated, thanks
An image file does not contain text, it is a binary file, calling File.ReadAllText probably messes up the encoding. Try:
var img = File.ReadAllBytes(att.Value);
var base64String = Convert.ToBase64String(img);
In addition, the request expects the body to just be a string. You are passing JSON. Your code should look like this:
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(base64String);
}

Cannot get back the DICOM metadata after decode from base64 string

I am sending DICOM images to my API by encoding as base64 from the frontend, which is in Angular CLI. Also, I have Rest API to get those encoded DICOM images and decode them back before had some process with them. But after decoding the DICOM image into the memory stream, metadata of DICOM images are lost. It is appreciatable if I got a better solution. Please find my codes below.
//Angular code
var file = event.dataTransfer ? event.dataTransfer.files[i] :
event.target.files[0];
//var pattern = /.dcm/;
var reader = new FileReader();
reader.onload = this._handleReaderLoaded.bind(this);
reader.readAsDataURL(file);
//Web API Code
[HttpPost("UploadFile/{Id}")]
public async Task<IActionResult> UploadFile(int Id, [FromBody] DICOMFiles
dicomfiles)
{
String base64Encoded = encodedImage;
string output =
encodedImage.Substring(encodedImage.IndexOf(',') + 1);
byte[] data = Convert.FromBase64String(output);
MemoryStream stream = new MemoryStream(data);
client.UploadFile(stream, "Projects/test_images/Test.dcm");
}
At last, I found a solution for this. The problem is not about decode from base64. The actual problem is with the client.UploadFile() method call.
Before using the client.uploadfile(), we need to make sure that the memory stream object is pointing to position "0". This will allow the client.UploadFile() method to create and write all the content of the mentioned file from the start of the byte[] array. we can do this as mentioned below.
stream.Position = 0;

zipInputStream.getNextEntry() always return null from stream that created from byte[]

Good day!
I have soap response message that contatined binary zip file. It looks like:
binary response
I try to parse zip-file:
byte[] bin = ExecutionUtil.getDynamicProcessProperty("binary").getBytes();
logger.warning("binary "+bin);
ZipInputStream zipStream = new ZipInputStream(new
ByteArrayInputStream(bin));
logger.warning("zipStream "+zipStream+" nextEntry "+zipStream.getNextEntry());
ExecutionUtil.getDynamicProcessProperty("binary").getBytes(); - this row make byte[] from string which contain binary from soap response.
When I try to test zipStream.getNextEntry() always return null.
I try to make
byte [] byteZip= child.getText().getBytes("UTF-8");
ZipInputStream zipStream = new ZipInputStream(newByteArrayInputStream(byteZip) or .Charset.forName("UTF-8"))
but I always have same result.
How I can get Entries from zipFile?

encrypt the audio file by android and decrypt it by backend sails js

I want to encrypt the audio file by android and decrypt it by backend sails js. I developed the program for that but I got error in sails js like
error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt
This is my source code for encrypt the audio file in android
final String ALGORITHM = "blowfish";
String keyString = "DesireSecretKey";
private void encrypt(String file) throws Exception {
File extStore = Environment.getExternalStorageDirectory();
File inputFile = new File(file);
File encryptedFile = new
File(extStore+"/Movies/encryptAudio.amr");
doCrypto(Cipher.ENCRYPT_MODE, inputFile, encryptedFile);
}
private void doCrypto(int cipherMode, File inputFile,
File outputFile) throws Exception {
Key secretKey = new
SecretKeySpec(keyString.getBytes(),ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(cipherMode, secretKey);
FileInputStream inputStream = new FileInputStream(inputFile);
byte[] inputBytes = new byte[(int) inputFile.length()];
inputStream.read(inputBytes);
byte[] outputBytes = cipher.doFinal(inputBytes);
FileOutputStream outputStream = new
FileOutputStream(outputFile);
outputStream.write(outputBytes);
inputStream.close();
outputStream.close();
}
I installed the crypto , fs libraries in sails js backend by following command
npm install crypto
npm install fs
This is my source code for decrypt the audio file in sails js
function decrypt() {
var crypto = require('crypto'),
algorithm = 'blowfish',
password = 'DesireSecretKey';
var fs = require('fs');
// input file
var r = fs.createReadStream(config.UPLOAD_FILES_PATH
+'/encryptAudio.amr');
var decrypt = crypto.createDecipher(algorithm, password,"");
// write file
var w = fs.createWriteStream(config.AUDIO_PATH+'decryptAudio.amr');
// start pipe
r.pipe(decrypt).pipe(w);
}
Encryption is working properly & i can get the encrypted audio file.But the issue is i couldn't get the decrypted audio file by sails js. Can you identify the issue?
maybe the answer to this question might help as you are using Java's library for cryptography this should pretty much guide you in right direction.
Encrypt with Node.js Crypto module and decrypt with Java (in Android app)
I would have mentioned this in comments section but I do not have enough reputation points to comment.
This is opposite of what you are trying to achieve but still it could help you to analyze your issue.

Javamail base64 decoding

I use javamail to get message, when I get the message i have:
com.sun.mail.util.BASE64DecoderStream,
I know that is part of multipart message, in the source of message I have
Content-Type: image/png; name=index_01.png
Content-Transfer-Encoding: base64
How encode this message??
edit:
I have that code:
else if (mbp.getContent() instanceof BASE64DecoderStream){
InputStream is = null;
ByteArrayOutputStream os = null;
is = mbp.getInputStream();
os = new ByteArrayOutputStream(512);
int c = 0;
while ((c = is.read()) != -1) {
os.write(c);
}
System.out.println(os.toString());
}
And that code return strange string, for example:
Ř˙á?Exif??II*????????????˙ě?Ducky???????˙á)
com.sun.mail.util.BASE64DecoderStream is platform dependent. You cannot rely on that always being the type of class that handles base64 decoding.
Rather the javamail APIs already support decoding for you:
// part is instanceof javax.mail.Part
ByteArrayOutputStream bos = new ByteArrayOutputStream();
part.getDataHandler().writeTo(bos);
String decodedContent = bos.toString()
What are you expecting when you read the contents of an image part? The image is stored in the message in an encoded format, but JavaMail is decoding the data before returning the bytes to you. If you store the bytes in a file, you can display the image with many image viewing/editing applications. If you want to display them with your Java program, you'll need to convert the bytes to an appropriate Java Image object using (e.g.) APIs in the java.awt.image package.
That Sun's base 64 encoder is in the optional package and can be moved or renamed at any time without warning, also may be missing in alternative Java runtimes, also access to these packages may be disabled. It is much better not to rely on it.
I would say, use Base64 from Apache Commons instead, should do the same. Hope you can rebuild and fix the source code.

Resources