I want to write one way to encrypt some data with a String key which is the best approach?
Encode and decode A string with Key. Suppose you have a string "ABCD" and a key "BC" then the output should be "BDDF".
Can some please guide me with this question?
Depends what level of security do you want
what you have described is a simple polyalphabetic substitution cipher and provides very little actual security (though it is a nice learning example, history lesson and good excercise trying to learn how to break it).
In that case you may have a finite group (an array) of characters and work with remainderless addition. Simple and working.
if you want to encrypt something more serious way, you may look for serious cryptography (in your case you need as well a pbkdf - password based key derivation function).
I have written a small tutorial you may have a look at
Related
I came to know about jBCrypt for hashing a password and storing in DB. But I didnt find any option to get back the actual value from the hashed value. Only BCrypt.checkpw(password, hashedPassword) is available which is returning boolean.http://www.mindrot.org/projects/jBCrypt/
How can I get the actual value out of hashed value.
If it is not possible in jBCrypt, is there any other way to encrypt and decrypt values in java? Thanks in advance...
Instead of using a hash function, you can use a symmetrical encryption algorithm, like offered by Spring Security, from their Crypto Module, more specifically their Encryptors class.
Here is a basic encryption/decryption example:
public static void main(String[] args) {
final String salt = UUID.randomUUID().toString().replace("-", "");
TextEncryptor textEncryptor = Encryptors.delux("my-super-secure-password-for-the-encryptor", salt);
final String passwordToBeEncrypted = "my-secure-password-to-be-encrypted";
final String encrypted = textEncryptor.encrypt(passwordToBeEncrypted);
textEncryptor.decrypt(encrypted);
System.out.println(passwordToBeEncrypted.equalsIgnoreCase(textEncryptor.decrypt(encrypted)));
}
Here, I am using the delux. As per their documentation:
Creates a text encryptor that uses "stronger" password-based
encryption.
Keep in mind that this is a very naive approach of encrypting and decrypting.
I would not recommend you copy paste this solution in your production code.
In order for this functionality to be production ready, you want the password provided to the Encryptors.delux() to be stored somewhere safe.
Also, you also want to use a different way of generating a salt for your password (potentially a salt for each new password encryption) and storing it for later where you want to decrypt your password.
Also, you might want to not keep the password in plain text (String), but keeping it as char[] or byte[], but this should give a start from where you can start.
There is also a different library that does the same, from Apache, Apache Commons Crypto, which does utilize the same algorithms as Spring Crypto.
Keep in mind, you are more safe in using a library instead of implementing yourself, since using package javax.crypto will require you to know what you are doing and not do more harm than needed.
Side note: You might bump into the situation that your jdk is limited to 128 bits. To benefit from the 256bits, make sure you add the Java Cryptography Extension
The definition of a hash function has resistance to preimages: given h(x), it should be impossible to recover x. A hash function being "reversible" is the exact opposite of that property. Therefore, you cannot reverse hash function hence it is not possible to get actual value from hashed value.You cannot get x from h(x),only thing you can do is for the coming new password y compute h(y) and see if it is equal to h(x).
Not just jBcrypt any secured hash function won't provide this functionality of recovery
But I didnt find any option to get back the actual value from the hashed value
Well - that's the primary purpose of the cryptographic hash functions.
is there any other way to encrypt and decrypt values in java? Thanks in advance...
There are a lot of examples to encrypt / decrypt values in Java, just search for it, even here on SO. You may as well have a look into my blog about encryption in Java - it's about basic low level crypto API.
I hope you don't mean to use encryption for user passwords - even remote possibity to make the passwords reversible would make your system potentially dangerous for leaks.
I'd like to validate that a String is a sha256 representation of another without having to decrypt it. Is this possible?
Yes and no.
You can test that a string is hex very easily. You can then test that it contains a statistically sensible number of digits and letters. That will rule out some common non sha256 strings.
But if someone creates a random string designed to look like a sha256, I don't think it's possible to distinguish it from the real thing by any mathematical test. The algorithm is designed to be robust to that.
A sha-256 value is just a 256 bits (32 bytes) value which you usually represent as a String or as a byte[] in Java.
As a value per se it's pointless, if you want to tell if a specific String is a hash then any 32 bytes number is a hash of an infinite unknown plain texts. But it's like asking "how do I know that a 32 bytes number is a number?", you see that you are going nowhere.
It's useful only when it's paired to a plain text so that you can compare it with the hash computed from the plain text to verify they match.
I think what you could do is to hash the other string and then compare these two strings with each other.
No idea if this would help you but I read that it was commonly used praxis when creating rainbow tables for cracking password attempts.
EDIT: Oh forgot this is also the way to compare passwords in php when you login to a webpage iirc. At least I had to do it like this for university.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I want to make a simple public-key(asymmetric) encryption. It doesn't have the be secure, I just want to understand the concepts behind them. For instance, I know simple symmetric ciphers can be made with an XOR. I saw in a thread on stackexchange that you need to use trapdoor functions, but I can't find much about them. I want to say, take a group of bytes, and be able to split them someway to get a public/private key. I get the ideas of a shared secret. Say, I generate the random number of 256(not random at all :P), and I split it into 200 and 56. If I do an XOR with 200, I can only decrypt with 200. I want to be able to split numbers random and such to be able to do it asymmetrically.
OK, just a simple demo-idea, based on adding/modulo operation.
Lets say we have a modulo value, for our example 256. This is a public-known, common value.
Let's say you generate a random secret private key in the interval [1-255], for example, pri=133.
Keep secret key in the pocket.
Generate a public key, pub = 256 - pri = 123. This public key (123)
you can share to the world.
Imagine, 3rd party does not know, how to compute the private key from a public. So, they know only public key (123).
Someone from the public wants to send you an encrypted ASCII-byte. He gets his byte, and adds to it the public key by modulo 256 operation:
encrypted = (input_value + pub) % modulto;
For example, I want to send you the letter "X", ASCII code = 88 in encrypted form.
So, I compute:
(88 + 123) % 256 = 211;
I am sending you the value 211 - encrypted byte.
You decrypt it by the same scheme with your private key:
decrypted = (input_value + pri) % 256 = (211 + 133) % 256 = 88;
Of course, using the simple generation pair in this example is weak, because of
the well-known algorithm for generating the private key from the public, and anybody can easily recover the private using the modulo and public.
But, in real cryptography, this algorithm is not known. But, theoretically,
it can be discovered in future.
This is an area of pure mathematics, there's a book called "the mathematics of cyphers" it's quite short but a good introduction. I do suggest you stay away from implementing your own though, especially in Java (you want a compiler that targets a real machine for the kind of maths involved, and optimises accordingly). You should ask about this on the math or computer-science stack-exchanges.
I did get a downvote, so I want to clarify. I'm not being heartless but cyphers are firmly in the domain of mathematics, not programming (even if it is discreet maths, or the mathsy side of comp-sci) it requires a good understanding of algebraic structures, some statistics, it's certainly a fascinating area and I encourage you to read. I do mean the above though, don't use anything you make, the people who "invent" these cyphers have forgotten more than you or I know, implement exactly what they say at most. In Java you ought to expect a really poor throughput btw. Optimisations involving register pressure and allocation pay huge dividends in cypher throughput. Java is stack-based for starters.
Addendum (circa 6 years on)
Java has improved in some areas now (I have a compiler fetish, it's proper weird) however looking back I was right but for the sort-of wrong reasons, Java is much easier to attack through timing, I've seen some great use of relying on tracing compiling techniques to work out what version of software is being used for example. It's also really hard to deal with Spectre which isn't going away any time soon (I like caches.... I feel dirty saying that now)
HOWEVER: above all, don't do this yourself! Toy with it AT MOST - it's very much in the domain of mathematics, and I must say it's probably better done on paper, unless you like admiring a terminal with digits spewn all over it.
http://en.wikipedia.org/wiki/RSA_(algorithm)
Is the standard one on which the (whole) internet is based
I'm looking for some ideas on an assignment.
I have 7 ciphertext files, all of which are encrypted using the same symmetric key, which is 3 characters long and is alphabetic. No encryption algorithm is provided but the specs state that it is a home-made algorithm and is naive (whatever that means). My objective is to decrypt these files. I'm merely looking for ideas on the attacks which I can carry out on these files.
So far, I have done a frequency analysis, brute force attack to detect Ceasar Cipher, Krasinsky's method to detect Vigenere Cipher, Ciphertext XOR to detect a simple version of the stream cipher. I suspect that the files were encrypted using some mix of ciphers.
By the way, the decrypted plaintext is supposed to contain just a plain message, but the ciphertext reveals the use of over 97 different ASCII symbols!
Any general help, ideas or directions are greatly appreciated! Honestly, I'm not expected to decrypt these files, but then I might as well prove my professor wrong with your help. Thanks!
EDIT
I'm looking for attacks on block or stream ciphers. At least thats what I suspect...
The famous Enigma machine used 3 character symmetric alphabetic keys. 97 ASCII symbols? ASCII runs from 32 to 126 giving 94 symbols. The \n and \r add two more for 96 and then an end of message marker such as \0 for 97. To put it another way, a naive copy of the early Engima machines (with a fixed reflector) encrypting Windows style textual data would match the clues very well.
The enigma machine has some known flaws. If your professor was being exceptionally kind he will have replicated the weak system used by the German Navy early on. This was to encrypt every message with a one time key, but then to allow decryption to transmit the one time key twice at the start of the message encrypted using a standard key. By transmitting it twice they provided extra context to the cryptanalysis.
The second well known flaw was that a character never maps to itself. Thus if you have a potential plain text no character will match.
It is possible to brute force Enigma if you know what the rotors and reflector look like. Without knowing that you have around 10^15 possibilities to explore in this case.
Why not go ahead and get started with brute forcing all of the 26**3 possibilities for each of the most popular symmetric key algorithms:
Twofish
Serpent
AES (Rijndael)
Blowfish
CAST5
And any others you can find.
Since the algorithm is simple and homemade, you might try these naive algorithms:
repeated XOR with the cipher key every 3rd character
repeated XOR with the cipher key every 2nd or 1st character
XOR and rotate/shift: the cipher key is xor'ed with the ciphertext and rotated/shifted
Since you know the plain text it to be regular text, look for patterns in the first few characters of ciphertext and see if they can be combined with the cipher key to arrive at a ASCII code for a letter/number.
Now, you said that you have done the statistical analysis. If algorithm is in fact naive, the frequencies of the symbols will not be uniformly distributed. Some symbols will be found more often. Is it the case? If so, I'd dig from there.
I might as well prove my professor
wrong with your help
With "our help" would be us proving your professor wrong.
Im writing a way of checking if a customers serial number matches my hard coded number. Is there a way of making this as hard to read as possible in case an undesirable gets their hands on the code?
I am working in java.
For instance (pseudo code)
if (x != y) jump out of code and return error
Cheers , apologies if this is a bit of an odd one
Security through obscurity is always a bad idea. You don't need to avoid it, but you should not trust solely on it.
Either encrypt your serials with a key you type in at startup of the service, or just specify the serials as hex or base64, not ASCII.
The normal way to do this would be to use a hash.
Create a hash of your serial code.
To validate the client serial, hash that using the same function.
If the hashes match, the serial was correct, even though the serial itself was not in the code.
By definition, a from the hash it's almost impossible to deduce the original code.
Making the code look complex to avoid being hacked never helps!
You can try SHA1 or some other one-way encrypting (MD5 not so secure but it's pretty good). Don't do this:
if (userPassword equals myHardCodedpassword)
Do this:
if (ENCRYPTED(userPassword) equals myhardcodedEncryptedpassword)
So the code-reader only can see an encrypted (and very very very difficult to decrypt) value.
Tangle the control structure of the released code?
e.g feed the numbers in at a random point in the code under a different variable and at some random point make them equal x and y?
http://en.wikipedia.org/wiki/Spaghetti_code
There is a wikipedia article on code obfuscation. Maybe the tricks there can help you =)
Instead of trying to make the code complex, you can implement other methods which will not expose your hard-coded serial number.
Try storing the hard coded number at some permanent location as encrypted byte array. That way its not readable. For comparison encrypt the client serial code with same algorithm and compare.