I wrote a small python script a while ago, which uses the python cryptography module to encrypt some data using fernet. To do this, it reads the data from a file as bytes, runs the Fernet(key).encrypt(data) method, which returns a byte-object which can then be saved to another file. This works perfectly, with text as well as with images, encryption as well as decryption.
However, I now wanted to make an app in kotlin (using the fernet-java8 library) to be able to decrypt my data without my computer. For that, I use the following function to retrieve the data from the file:
val input: InputStream? = data!!.data?.let { getContentResolver().openInputStream(it) }
val inputAsString = input?.bufferedReader().use { it?.readText() }
This code is more or less copied together from various posts. The data is then decrypted using this method:
fun decrypt(decabledata:String){
println(decabledata.toString())
val token=Token.fromString(decabledata)
//val token=decabledata
//val token= Token.fromString("gAAAAABj512Pcv-sxoGmeeI5oM-a_GSOSUORKjxrp1QEtZH97Gv0XpYFTcMS2MDD8bPBTI_WYbadmG7dcdqE72ySNx_9K6A2sA==")
val fernetKey=Key("MYKEY")
val validator: Validator<String> = object : StringValidator {
#RequiresApi(Build.VERSION_CODES.O)
override fun getTimeToLive(): TemporalAmount {
//val timere:Long = 24
return Duration.ofSeconds(Instant.MAX.getEpochSecond())
}
}
val data = token.validateAndDecrypt(fernetKey, validator)
val resview=findViewById(R.id.textView1) as TextView
resview.setText(data.toString())
println(data)
}
This also works perfectly when decrypting text files. However, when I try to decrypt an image, the resulting file (which is then saved to Downloads) is not properly working and it cant be displayed. This makes (kind of) sense, because everything in this method is a string (Although when going by the python script, you would not need to distinct between the type of data). But when I try to change the method Token.fromString() to Token.fromBytes() and give a ByteArray object instead of a String, the method crashes with the following exception:
Process: com.example.cryptomobile, PID: 12020
java.time.DateTimeException: Instant exceeds minimum or maximum instant
at java.time.Instant.create(Instant.java:405)
at java.time.Instant.ofEpochSecond(Instant.java:298)
at com.macasaet.fernet.Token.fromBytes(Token.java:136)
at com.example.cryptomobile.MainActivity.decrypt(MainActivity.kt:120)
Quite frankly, I have no idea whatsoever what this is supposed to mean or how I can fix it. I don't necessarily need to use the fromBytes method, if the picture decryption works with the fromString method too and my mistake is somewhere else, tell me and I will find it. Otherwise, any help on how I can decrypt pictures and text and/or fix or evade this exception would be greatly appreciated.
If you need any additional information on my code, feel free to tell me, I am not very experienced on StackOverflow.
Thanks in advance.
Related
I've been a Java developer for many years developing mostly MVC Web applications using Spring. I am learning Kotlin and Android as a self development project, and mostly love it. I normally just figure things out, but I think I am missing something big here (as I like writing code that is easy to maintain and not prone to Exceptions). I understand the inter-operability with Java, I'm just confused on how my Kotlin code compiles and gives me no sort of warning whatsoever that a Java method call throws an Exception.
Here is a very simple example I have from the Android Tutorials on how to write a file that demonstrates this issue (From Camera Intent Tutorial). File.createTempFile() throws IO Exception in Java but Kotlin allows me to just call this method as if nothing throws any exceptions at all. If I remove the #Throws annotation on the method I get no warning that I'm calling a method that has the potential to throw an Exception.
#Throws(IOException::class)
private fun createImageFile(): File {
// Create an image file name
val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
val storageDir: File = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
return File.createTempFile(
"JPEG_${timeStamp}_", /* prefix */
".jpg", /* suffix */
storageDir /* directory */
).apply {
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = absolutePath
}
}
I'm just confused on how I am supposed to keep track of Java methods that throw Exceptions. I know a lot of Exceptions and this example has the Exception in it, but by no means do I know (or could I know) every Exception possible for every method call in Java and/or Java libraries. Am I supposed to go look at the source code of every method I call to make sure I am not missing an Exception? That seems very tedious and quite a bit of overhead on a large scale codebase.
This is called perfectly fine from my code without the #Throws annotation even though it throws IO Exception in Java. How am I supposed to know if a Java method is throwing an Exception I need to take into account while coding (without looking at the source code)?
private fun createImageFile(): File {
// Create an image file name
val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
val storageDir: File = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
return File.createTempFile(
"JPEG_${timeStamp}_", /* prefix */
".jpg", /* suffix */
storageDir /* directory */
).apply {
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = absolutePath
}
}
I have read the documents on Exceptions and on Java inter-operability, I am just wondering if there is an easier way to tell if a Java method throws an Exception then looking at the source code (maybe I missed something)?
https://kotlinlang.org/docs/reference/java-interop.html
https://kotlinlang.org/docs/reference/exceptions.html
//Checked Exceptions
//In Kotlin, all exceptions are unchecked, meaning that the compiler does not force you to catch any
//of
// them. So, when you call a Java method that declares a checked exception, Kotlin does not force you
//to
//do anything:
fun render(list: List<*>, to: Appendable) {
for (item in list) {
to.append(item.toString()) // Java would require us to catch IOException here
}
}
I suggest you check with Intellij. If I use a method throwing an exception in my code, It hints me. It also suggests me to include throws Exception my method definition
Consider there are 3 methods,
A()throws Exception;
B(); //which calls A inside
C();// which calls B inside
This code will compile in Java without complaining. But it's not the best practice, throw Exception is much important like return type in the method definition. Especially in multi-developer projects. It improves usability and documentation.
Am I supposed to go look at the source code of every method I call to make sure I am not missing an Exception?
While using external libs, you don't need to know about the source code but you must refer the documentation to know about its behaviours.
what's the purpose of the method.
Whether it throws Exception or not. If so, Should I handle it or not.
The return type, which you obviously know.
I am working in a repository maintained by 200 developers. And we also practice the above.
And in addition, Java reflection has the library Method.getExceptionTypes() which will list you all the exceptions throwing by a method in runtime.
Note: I am Java developer and don't know much about Kotlin grammars
Since Kotlin doesn't support checked exceptions, you're out of luck when using a Java library. You just have to be diligent about looking at the docs of methods you're calling.
If you're writing a Kotlin library, you can box your result in a class that wraps a successful result or an error. Or you can use sealed classes. For example:
sealed class QueryResult
class Success(val result: List<String>): QueryResult()
class IncorrectSyntaxError(val msg: String): QueryResult()
class ConnectionError(val msg: String): QueryResult()
And then your function can return one of the above subclasses. The receiver can then use a when statement to handle the result:
var result: List<String>? = null
val query = doQuery()
when (query ) {
is Success -> result = query.result
is IncorrectSyntaxError -> showErrorMessage(query.msg)
is ConnectionError -> showErrorMessage(query.msg)
}
I have built an alloy model where I have put all my system logic. I want to do a large scale analysis. For doing that, my logic is to use Java to read the data file, then pass those data to Alloy to check whether those met the constraint I defined in the Alloy or not. To do that, my logic is to create sig object using those data and pass those to Alloy.
As my system model is complex, I am trying to summarize my problem using the following code-
sig A{
val: Int
}
sig B{
chunk: Int
}
fact {
A.val > 10 && A.val < 15
}
Now, I want to pass the following sig object and run command from Java.
sig C{
name: String
}
run {} for 4
How can I pass that code? I am following this link https://github.com/ikuraj/alloy/blob/master/src/edu/mit/csail/sdg/alloy4whole/ExampleUsingTheAPI.java . But not able to figure it out.
There is currently a branch pkriens/api in progress that makes this quite easy. Look at the testcases in the classic test project.
We're working on integrating this in the master branch soon (before the end of 2019).
I am trying to be able to pick out frames (video and metadata) from MPEG, MPEG-TS and MPEG-PS files and live streams (network / UDP / RTP streams). I was looking into using JCODEC to do this and I started off by trying to use the FrameGrab / FrameGrab8Bit classes, and ran into an error that those formats are "temporarily unsupported". I looked into going back some commits to see if I could just use older code, but it looks like both of those files have had those formats "temporarily unsupported" since 2013 / 2015, respectively.
I then tried to plug things back into the FrameGrab8Bit class by putting in the below code...
public static FrameGrab8Bit createFrameGrab8Bit(SeekableByteChannel in) throws IOException, JCodecException {
...
SeekableDemuxerTrack videoTrack = null;
...
case MPEG_PS:
MPSDemuxer psd = new MPSDemuxer(in);
List tracks = psd.getVideoTracks();
videoTrack = (SeekableDemuxerTrack)tracks.get(0);
break;
case MPEG_TS:
in.setPosition(0);
MTSDemuxer tsd = new MTSDemuxer(in);
ReadableByteChannel program = tsd.getProgram(481);
MPSDemuxer ptsd = new MPSDemuxer(program);
List<MPEGDemuxerTrack> tstracks = ptsd.getVideoTracks();
MPEGDemuxerTrack muxtrack = tstracks.get(0);
videoTrack = (SeekableDemuxerTrack)tstracks.get(0);
break;
...
but I ran into a packet header assertion failure in the MTSDemuxer.java class in the parsePacket function:
public static MTSPacket parsePacket(ByteBuffer buffer) {
int marker = buffer.get() & 0xff;
int marker = by & 0xff;
Assert.assertEquals(0x47, marker);
...
I found that when I reset the position of the seekable byte channel (i.e.: in.setPosition(0)) the code makes it past the assert, but then fails at videoTrack = (SeekableDemuxerTrack)tstracks.get(0) (tstracks.get(0) cannot be converted to a SeekableDemuxerTrack)
Am I waisting my time? Are these formats supported somewhere in the library and I am just not able to find them?
Also, after going around in the code and making quick test applications, it seems like all you get out of the demuxers are video frames. Is there no way to get the metadata frames associated with the video frames?
For reference, I am using the test files from: http://samples.ffmpeg.org/MPEG2/mpegts-klv/
In case anyone in the future also has this question. I got a response from a developer on the project's GitHub page to this question. Response:
Yeah, MPEG TS is not supported to the extent MP4 is. You can't really seek in TS streams (unless you index the entire stream before hand).
I also asked about how to implement the feature. I thought that it could be done by reworking the MTSDemuxer class to be built off of the SeekableDemuxerTrack so that things would be compatible with the FrameGrab8Bit class, and got the following response:
So it doesn't look like there's much sense to implement TS demuxer on top of SeekableDemuxerTrack. We haven't given much attention to TS demuxer actually, so any input is very welcome.
I think this (building the MTSDemuxer class off of the SeekableDemuxerTrack interface) would work for files (since you have everything already there). But without fully fleshing out that thought, I could not say for sure (it definitely makes sense that this solution would not work for a live MPEG-TS / PS connection).
I'm currently working on an application built in Scala with Spray routing.
So for dealing with a JSON document sent over POST, it's pretty easy to access the variables within the body, as follows;
respondWithMediaType(`application/json`) {
entity(as[String]) { body =>
val msg = (parse(body) \ "msg").extract[String]
val url = (parse(body) \ "url").extractOpt[String]
However, I'm now trying to write an additional query with GET, and am having some issues accessing the parameters sent through with the query.
So, I'm opening with;
get {
respondWithMediaType(`application/json`) {
parameterSeq { params =>
var paramsList = params.toList
So, this works well enough in that I can access the GET params in a sequential order (just by accessing the index) - the problem is, unfortunately I don't think we can expect GET params to always be sent in the correct order.
The list itself prints out in the following format;
List((msg,this is a link to google), (url,http://google.com), (userid,13))
Is there any simple way to access these params? For example, something along the lines of;
var message = paramsList['msg']
println(message) //returns "this is a link to google"
Or am I going about this completely wrong?
Apologies if this is a stupid question - I've only switched over to Scala very recently, and am still getting both acquainted with that, and re-acquainted with Java.
What I usually do is use the parameters directive to parse the data out to a case class which contains all the relevant data:
case class MyParams(msg: String, url: String, userId: Int)
parameters(
"msg".as[String],
"url".as[String],
"userId".as[Int]
).as[MyParams] {
myParams =>
// Here you have the case class containing all the data, already parsed.
}
To build your routes you could use the parameters directives. I'm not sure if this is what you're looking for, anyway you could use them as:
get {
parameters('msg) { (msg) =>
complete(s"The message is '$msg'")
}
}
Spray directives can be easily composed so you can use combine them in any way you want.
I hope that helps you.
I downloaded Calabash XML a couple of days back and got it working easily enough from the command prompt. I then tried to run it from Java code I noticed there was no API (e.g. the Calabash main method is massive with code calls to everywhere). To get it working was very messy as I had to copy huge chunks from the main method to a wrapper class, and divert from the System.out to a byte array output stream (and eventually into a String) i.e.
...
ByteArrayOutputStream baos = new ByteArrayOutputStream (); // declare at top
...
WritableDocument wd = null;
if (uri != null) {
URI furi = new URI(uri);
String filename = furi.getPath();
FileOutputStream outfile = new FileOutputStream(filename);
wd = new WritableDocument(runtime,filename,serial,outfile);
} else {
wd = new WritableDocument(runtime,uri,serial, baos); // new "baos" parameter
}
The performance seems really, really slow e.g. i ran a simple filter 1000 times ...
<p:filter>
<p:with-option name="select" select="'/result/meta-data/neighbors/document/title'" />
</p:filter>
On average each time took 17ms which doesn't seem like much but my spring REST controller with calls to Mongo DB and encryption calls etc take on average 3/4 ms.
Has anyone encountered this when running Calabash from code? Is there something I can do to speed things up?
For example, I this is being called each time -
XProcRuntime runtime = new XProcRuntime(config);
Can this be created once and reused? Any help is appreciated as I don't want to have to pay money to use Calamet but really want to get Xproc working from code to an acceptable performance.
For examples on how you could integrate XMLCalabash in a framework, I can mention Servlex by Florent Georges. You'd have to browse the code to find the relevant bit, but last time I looked it shouldn't be too hard to find:
http://servlex.net/
XMLCalabash wasn't build for speed unfortunately. I am sure that if you run profile, and can find some hotspots, Norm Walsh would be interested to hear about it.
Alternative is to look into Quixprox, which is derived from XMLCalabash:
https://code.google.com/p/quixproc/
I am also very sure that if you can send Norm a patch to improve the main class for better integration, he'd be interested to hear about it. In fact, the code should be on github, just fork it, fix it, and do a pull request..
HTH!