Last active
August 29, 2015 14:03
-
-
Save aserrallerios/3682b1f2a20639c5ab6e to your computer and use it in GitHub Desktop.
crypto auth java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.nio.charset.Charset; | |
import java.security.MessageDigest; | |
import java.security.NoSuchAlgorithmException; | |
import java.security.spec.InvalidKeySpecException; | |
import java.util.Arrays; | |
import javax.crypto.SecretKeyFactory; | |
import javax.crypto.spec.PBEKeySpec; | |
import org.apache.shiro.codec.Base64; | |
import org.apache.shiro.crypto.UnknownAlgorithmException; | |
public class Main { | |
public static void main(String[] args) throws NoSuchAlgorithmException, | |
InvalidKeySpecException { | |
String dbPass = "xxl6IyfCeQAbsxB4GcDjll1XmpP7NaBY"; | |
String dbSalt = "BhhtltEN7wGQOV1mfqZhynxe6ITeBB9o"; | |
byte[] passBytes = Base64.decode(dbPass); | |
byte[] saltBytes = dbSalt.getBytes(Charset.forName("UTF-8")); | |
byte[] testHash = | |
pbkdf2("123qweWQ".toCharArray(), saltBytes, 1000, passBytes.length); | |
byte[] testHashJS = hash("123qweWQ".getBytes(), saltBytes, 1000); | |
byte[] testHashJSDecoded = | |
hash("123qweWQ".getBytes(), Base64.decode(saltBytes), 1000); | |
System.out.println("CRYPTO: " + Arrays.equals(testHash, passBytes)); | |
System.out.println("JAVA SECURITY: " | |
+ Arrays.equals(testHashJS, passBytes)); | |
System.out.println("JAVA SECURITY DECODED: " | |
+ Arrays.equals(testHashJSDecoded, passBytes)); | |
} | |
public static byte[] pbkdf2(char[] password, byte[] salt, int iterations, | |
int bytes) throws NoSuchAlgorithmException, InvalidKeySpecException { | |
PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, bytes * 8); | |
SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); | |
return skf.generateSecret(spec).getEncoded(); | |
} | |
protected static byte[] hash(byte[] bytes, byte[] salt, int hashIterations) | |
throws UnknownAlgorithmException, NoSuchAlgorithmException { | |
MessageDigest digest = MessageDigest.getInstance("SHA-1"); | |
if (salt != null) { | |
digest.reset(); | |
digest.update(salt); | |
} | |
byte[] hashed = digest.digest(bytes); | |
int iterations = hashIterations - 1; // already hashed once above | |
// iterate remaining number: | |
for (int i = 0; i < iterations; i++) { | |
digest.reset(); | |
hashed = digest.digest(hashed); | |
} | |
return hashed; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment