How to find keylength of SSH RSA keys using java - java

I am using JSCH API to find length of RSA SSH keys .
I use the following code to do that:
KeyPairRSA KPR = (KeyPairRSA) KeyPairRSA.load(jsch, keypath);
System.out.println("size " +KPR.getKeySize());
This returns me always length 1024 .I think its bug with API itself.
Can anyone please tell me how to find length of RSA/DSA SSH keys?
Thanks a lot in advance.

I'm the author of JSch.
It is a bug or the incompleteness of KeyPair* classes.
They had been just introduced for the key-pair generation purposes.
But, in our internal development version, KeyPair* classes have been overhauled, and
that method has worked well.
# This is off-topic, but we have added the support for Putty's private key format, as a bonus! :-)
Anyway, the fix will be available in the next release, and if you can't wait for it,
replace KeyPairRSA#getKeySize() with the following,
public int getKeySize(){
return (new java.math.BigInteger(n_array)).bitLength();
}

Related

How to use an OnlineTSPSource with esig/dss Library?

I'm attempting to use an online timestamp authority (rfc3161) with the Digital Signature Service Java library. However, the following snippet (from their test cases, and similar to the one from their Cookbook):
String tspServer = "http://tsa.belgium.be/connect";
OnlineTSPSource otsp = new OnlineTSPSource(tspServer);
/* tried setting otsp.setDataLoader(new TimestampDataLoader());
too, as it defaults to otsp.setDataLoader(new
NativeHTTPDataLoader()); the exception happens in both cases */
byte[] digest = DSSUtils.digest(DigestAlgorithm.SHA1, "Hello world".getBytes());
TimeStampToken timeStampResponse =
otsp.getTimeStampResponse(DigestAlgorithm.SHA1, digest);
always ends with the following exception:
eu.europa.esig.dss.DSSException:
java.util.concurrent.ExecutionException: java.lang.NoSuchMethodError:
org.apache.commons.io.IOUtils.closeQuietly(Ljava/io/Closeable;)V
Already tried many different public rfc3161 servers (some listed here). Sure there's something wrong going on there, but, as a beginner, I cannot understand what is wrong (what method should be there).
If anyone could put me in the right direction to get the snippet working (or even be kind enough to comment a reliable startup guide on cades/xades/pades with Java's bouncycastle) I would be really grateful.
As stated in the comments by Marteen Bodewes and Mark Rotteveel, there was something wrong with the version of Apache Commons-IO in the classpath. The project is set using Apache Maven and there was an old Commons-IO version declared there as a dependency. In this case, it was enough to remove that declaration, so Maven could download the appropriate version that was declared as an esig/DSS dependency.
esig/DSS version was 5.4 at the time.

How to decrement an IPV4 address using java library?

I am converting a nodejs code into Java8.
In node there are code as shown below
var ipToEndAt = ippp.prev("192.168.1.225");
result of ipToEndAt is "192.168.1.224"
I need to convert this line into a java code. I searched for SubnetUtils library, but couldn't find anything appropriate.
similar i also need to increment ip address by 1
can anyone suggest a library or a code snippet ? which ever would be best
Although it's not overly hard to do it yourself, there's an InetAddresses class in Guava that allows this kind of operations. And Guava is a very useful addition to your toolchest anyways.
InetAddress address = InetAddress.getByName("192.168.1.225");
address = InetAddresses.decrement(address);
See, that looks almost identical to the JS code.
In your comment you state that you are unable to use the decrement method, which indicates that you have a really old version of Guava.
https://github.com/google/guava/commit/d39130651d8a90f5ebe066de7f0b2311806e5152#diff-1207ec0a4b5d3f5e5c2236b7373eefc9
The project home page contains instructions on how to add the current version (25.1) to your project's dependencies.
This can be done with the IPAddress Java library, in a manner that is polymorphic between IPv4 and IPv6. Also, it is not limited to incrementing or decrementing by 1 as with Guava, you can use any long value and catch AddressValueException in the case of overflow. Disclaimer: I am the project manager of IPAddress.
Sample code:
IPAddress result = increment("192.168.1.225", -1);
System.out.println(result);
result = increment("::", 1);
System.out.println(result);
static IPAddress increment(String addrStr, long inc) throws AddressValueException {
return new IPAddressString(addrStr).getAddress().increment(inc);
}
Output:
192.168.1.224
::1
More elaborate sample code at the IPAddress wiki

How can I make bcrypt in php and jbcrypt in java compatible

I want to make register page in php and make the password hashed with bcrypt and put in database.
I also want to make a login system in Java, and get the password in the same password, using jbcrypt.
How can I make jbcrypt and bcrypt in php compatible, with the same salt.
you can check out this:
https://github.com/ircmaxell/password_compat/issues/49
that's worked for me:
public static void main(String[] args) {
//Laravel bcrypt out
String hash_php = "$2y$10$ss9kwE8iSIqcJOAPhZR0Y.2XdYXJTFJ1/wGq6SUv74vULE7uhKUIO".replaceFirst("2y", "2a");
System.out.println("hash php " + hash_php);
//String a_hash = BCrypt.hashpw("123456", BCrypt.gensalt());
//System.out.println("Encrypt " + a_hash);
if (BCrypt.checkpw("123456", hash_php)) {
System.out.println("It matches");
} else {
System.out.println("It does not match");
}
//mtPruebaRecuperarClave();
}
Console - OutPut
I hope that's help You.
The problem is that PHP with it's password_hash() has it's own version scheme due to the fact that previous implementations had breaking bugs and it should be possible to recognize the old hashes.
So the version used by OpenBSD is $2a$ (will be $2b$ in future releases) and password_hash() uses $2y$ (previously $2x$), so of course the has will not match e.g.
$2y$10$ss9kwE8iSIqcJOAPhZR0Y.2XdYXJTFJ1/wGq6SUv74vULE7uhKUIO
vs
$2a$10$ss9kwE8iSIqcJOAPhZR0Y.2XdYXJTFJ1/wGq6SUv74vULE7uhKUIO
(see the wikipedia article about more info on the versions)
Currently jBcrypt (0.4) only supports $2a$.
There are 2 possibilities:
1. Replace the version identifier manually before passing it to jBcrypt (hack)
String hash_php = "$2y$10$ss9kwE8iSIqcJOAPhZR0Y.2XdYXJTFJ1/wGq6SUv74vULE7uhKUIO".replaceFirst("$2y$", "$2a$");
2. Using a different implemention supporting custom version identifier
This is the reason I implemented a new library for bcrypt (based on jBcrypt). https://github.com/patrickfav/bcrypt
Just use it like this (it does not verify for version per default, you can use verifyStrict() in that case)
BCrypt.Result result = BCrypt.verifyer().verify(password.toCharArray(), "$2y$10$ss9kwE8iSIqcJOAPhZR0Y.2XdYXJTFJ1/wGq6SUv74vULE7uhKUIO")
if(result.verified) {...}
If you want bcrypt to create $2y$ hashes:
String bcryptHash = BCrypt.with(BCrypt.Version.VERSION_2Y).hashToString(6, password.toCharArray());
// $2y$10$ss9kwE8iSIqcJOAPhZR0Y.2XdYXJTFJ1/wGq6SUv74vULE7uhKUIO
Full Disclaimer: Im the author of bcrypt
If you remove the first 7 chars from the hashes ($2y$10$ / $2a$10$) the rest should be the same regardless of the programming language you have used. The first characters of the generated hash is a prefix that tells more about the hash algorithm.
In your example, the $2y$ and $a2$ are defining the algorithm of the hash, and the 10$ is the "cost" of the hash generation (how many times the hash algorithm was repeatedly applied or something like this).
If you want to learn more about the prefixes in the bcrypt generated hashes, read this article.

ESAPI Symmetric Encryption using JavaEncryptor

I am testing basic stuff in ESAPI, and I ran across this symmetric encryption tutorial and copied and pasted the code, (along with importing the ESAPI 2.1.0 jar file, ESAPI.properties and validation.properties in the 'src' directory in Eclipse)
Modified code from the tutorial:
import org.owasp.esapi.crypto.CipherText;
import org.owasp.esapi.crypto.PlainText;
import org.owasp.esapi.errors.EncryptionException;
import org.owasp.esapi.reference.crypto.JavaEncryptor;
public class ESAPIsymEncTester {
public static void main(String[] args) throws EncryptionException{
String myplaintext = "My plaintext";
CipherText ciphertext =
JavaEncryptor.getInstance().encrypt( new PlainText(myplaintext) );
PlainText recoveredPlaintext = JavaEncryptor.getInstance().decrypt(ciphertext);
assert myplaintext.equals( recoveredPlaintext.toString() );
System.out.println("recovered plaintext: " + recoveredPlaintext.toString());
}
}
However, when I run this in Eclipse Luna using Java 1.8, I get this stack trace:
Exception in thread "main" org.owasp.esapi.errors.EncryptionException: Encryption failure: Invalid key exception.
at org.owasp.esapi.reference.crypto.JavaEncryptor.encrypt(JavaEncryptor.java:526)
at org.owasp.esapi.reference.crypto.JavaEncryptor.encrypt(JavaEncryptor.java:338)
at com.fate.engine.test.ESAPIsymEncTester.main(ESAPIsymEncTester.java:15)
Caused by: java.security.InvalidKeyException: Invalid AES key length: 96 bytes
at com.sun.crypto.provider.AESCipher.engineGetKeySize(AESCipher.java:495)
at javax.crypto.Cipher.passCryptoPermCheck(Cipher.java:1062)
at javax.crypto.Cipher.checkCryptoPerm(Cipher.java:1033)
at javax.crypto.Cipher.init(Cipher.java:1367)
at javax.crypto.Cipher.init(Cipher.java:1301)
at org.owasp.esapi.reference.crypto.JavaEncryptor.encrypt(JavaEncryptor.java:504)
... 2 more
I am not sure if this is a bug in the JavaEncryptor.java code, or if I am pulling something that I misconfigured from the ESAPI.properties file.
I replaced the master key and salt by running the JavaEncryptor and copy/pasting the resultant key/salt.
If it is a bug, I will email the ESAPI guys to get clarification on how I can fix it, since I looked through the JavaEncryptor code and am not entirely clear where all of the pieces are coming from.
Encryptor.MasterKey=WppLubGgsc/p6HhvcPf2LA==
Encryptor.MasterSalt=YokRN9mjMUTZspEbzBY90NA6EC8=
Encryptor.PreferredJCEProvider=
Encryptor.EncryptionAlgorithm=AES
Encryptor.CipherTransformation=AES/CBC/PKCS5Padding
Encryptor.cipher_modes.combined_modes=GCM,CCM,IAPM,EAX,OCB,CWC
Encryptor.cipher_modes.additional_allowed=CBC
Encryptor.EncryptionKeyLength=128
Encryptor.ChooseIVMethod=random
Encryptor.fixedIV=0x000102030405060708090a0b0c0d0e0f
Encryptor.CipherText.useMAC=true
Encryptor.PlainText.overwrite=true
Encryptor.HashAlgorithm=SHA-512 *****
Encryptor.HashIterations=1024
Encryptor.DigitalSignatureAlgorithm=SHA1withDSA
Encryptor.DigitalSignatureKeyLength=1024
Encryptor.RandomAlgorithm=SHA1PRNG
Encryptor.CharacterEncoding=UTF-8
Encryptor.KDF.PRF=HmacSHA1 *****
You forgot to place the most important part of your log into the question:
Dec 11, 2015 8:05:24 AM org.owasp.esapi.reference.JavaLogFactory$JavaLogger log
WARNING: [SECURITY FAILURE Anonymous:null#unknown -> /JavaEncryptor] Encryption key length mismatch. ESAPI.EncryptionKeyLength is 128 bits, but length of actual encryption key is 24 bits. Did you remember to regenerate your master key (if that is what you are using)???
This is a clue that there is something here that the library expects you to do.
It seems to me that you probably have the default encryptor properties set like this in esapi.properties:
Encryptor.MasterKey=owasp1
Encryptor.MasterSalt=testtest
The class JavaEncryptor has a main method that will generate valid properties for you. Run it in eclipse or via the command line. It will give you values to replace in esapi.properties, like this:
Dec 11, 2015 8:10:25 AM org.owasp.esapi.reference.JavaLogFactory$JavaLogger log
OFF: [SECURITY AUDIT Anonymous:null#unknown -> /SecurityProviderLoader] No Encryptor.PreferredJCEProvider specified.
SecurityConfiguration for Encryptor.EncryptionKeyLength not an integer in ESAPI.properties. Using default: 128
Generating a new secret master key
use '-print' to also show available crypto algorithms from all the security providers
SecurityConfiguration for Encryptor.EncryptionKeyLength not an integer in ESAPI.properties. Using default: 128
Copy and paste these lines into your ESAPI.properties
#==============================================================
Encryptor.MasterKey=qW0Qw+8eb1Zu1MBv5djwqA==
Encryptor.MasterSalt=b0VappFU1Hd6LjIt+TGYqQlfrdU=
#==============================================================
Once I did that, your code example runs just fine.
Here's what I'm going to suggest... grab the TEST version of ESAPI.properties from GitHub ("wget https://github.com/ESAPI/esapi-java-legacy/blob/master/src/test/resources/esapi/ESAPI.properties" should work, you use 'git' or save if from your browser), put it in place, and first use it AS-IS. If it fails, then there is a problem in you tweaked code. If it works, there was a problem in your ESAPI.properties file. Many people already suggested what to look for in terms of what might be wrong, but the differences should be minor enough that you should be able to spot them by diff'ing yours versus the TEST version in src/test/resources/esapi/ESAPI.properties. (The production version, incidentally, is under 'configuration/esapi/ESAPI.properties' and is not included with the jar because of some bug in the pom.xml which I don't know how to fix as I am not a Maven guru.)
If you have further questions, contact me at my Gmail account which you should be able to find easily enough via Google with my name and the term "OWASP". Once we figure out an answer that works for you, either you or I can post an answer back to Stack Overflow, but I don't frequent this forum enough to regularly monitor it. (Although, come to think of it, I probably do get notified of replies.)
Hope this helps,
-kevin w. wall / ESAPI crypto developer and co-project lead

Java Netscape LDAP Delete

I have been using the Java Netscape LDAP library to modify LDAP entries (http://www.mozilla.org/directory/javasdk.html). I now need a way to delete an entry. I looked through the library but could not find anything that I think would work.
Found “LDAPDelete” but that looks like it’s used from the command line.
If someone could post some sample code of how do this with an object ID it would very helpful.
ADDED:
After searching and finding the object I used the return value from getDN() method as the DN string.
Take a look at LDAPConnection.delete(java.lang.string dn) Thats what you should be using to delete an entry.
In pseudo code:
LDAPConnection myCon = new LDAPConnection("192.168.1.1",389);
myCon.delete("cn=Alan,ou=engineers,dc=fool,dc=com");
You'll have to javify that example, but that should work.
Netscape Directory API Documentation

Categories