public static String deskripsi(String chiperText, String key) {
try {
SecretKeySpec KS = new SecretKeySpec(key.getBytes(), "Blowfish");
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.DECRYPT_MODE, KS);
byte[] decrypted = cipher.doFinal(Base64.decode(chiperText, Base64.NO_PADDING));
return new String(decrypted);
} catch (Exception e) {
return "ERROR";
}
}
How to write code to search for manual calculation blowfish algorithm to encrypt a message??
Related
I am using Spring Boot to process certificate and client postman to interact with service, assumption privatekey, publickey and certificate has been process decrypted, then using CertificateHelper getCertificate() function to parseX509Certificate
private List<Certificate> getCA(X509Certificate cert, Date tsp) {
Security.addProvider(new BouncyCastleProvider());
try {
String cnIssuer = X500Name.asX500Name(cert.getIssuerX500Principal()).getCommonName();
int xTry = 0;
while ((resultCA == null || resultCA_C5 == null || resultCA_C3 == null || resultCA_v1 == null) && xTry <= 3) {
LOGGER.info(LogSystem.getLog("TRY :" + xTry, tsp, "LOG"));
try {
loadCAinit();
} catch (KeyManagementException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnrecoverableKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (CertificateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (KeyStoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchProviderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
xTry++;
}
if (xTry > 3) {
return null;
}
for (int i = 0; i < 4; i++) {
List<Certificate> CACheck;
if (i == 0) {
CACheck = resultCA;
} else if (i == 1) {
CACheck = resultCA_C3;
} else if (i == 2) {
CACheck = resultCA_C5;
} else {
CACheck = resultCA_v1;
}
LOGGER.info(LogSystem.getLog("CA CHECK : " + CACheck.get(0).toString(), tsp, "LOG"));
X509Certificate certCA;
try {
LogSystem.info("Process getcertificate on certificate helper");
certCA = (X509Certificate) CertificateHelper.getCertificate(CACheck.get(0).getCertificateData());
LogSystem.info("End process getcertificate on certificate helper");
String cnIssuerCheck = X500Name.asX500Name(certCA.getSubjectX500Principal()).getCommonName();
System.out.println(" CA CN: " + cnIssuerCheck);
System.out.println("User Issuer CN: " + cnIssuer);
if (cnIssuer.equals(cnIssuerCheck)) {
LOGGER.info(LogSystem.getLog("DN CA:" + certCA.getSubjectDN().toString() + ", SN: " + certCA.getSerialNumber().toString(16).toUpperCase(), tsp, "LOG"));
LOGGER.info(LogSystem.getLog("DN User:" + cert.getSubjectDN().toString() + ", SN: " + cert.getSerialNumber().toString(16).toUpperCase(), tsp, "LOG"));
return CACheck;
}
} catch (CertificateException e) {
// TODO Auto-generated catch block
LOGGER.info(LogSystem.getLog(" CATCH 1", tsp,"LOG"));
e.getCause();
e.printStackTrace();
System.out.println("asas");
}
}
LOGGER.info(LogSystem.getLog("Issuer " + cnIssuer + " not found : " + cert.getIssuerDN(), tsp, "LOG"));
System.out.println("asas");
} catch (IOException e) {
// TODO Auto-generated catch block
LOGGER.info(LogSystem.getLog(" CATCH 2", tsp,"LOG"));
e.printStackTrace();
System.out.println("asas");
}
LOGGER.info(LogSystem.getLog(" RETURN NULL", tsp,"LOG"));
System.out.println("asas");
return null;
}
getCertificate() function on class CertificateHelper
package org.ejbca.core.protocol.ws.common;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import org.cesecore.util.Base64;
import org.cesecore.util.CertTools;
public class CertificateHelper {
public static final String RESPONSETYPE_CERTIFICATE = "CERTIFICATE";
public static final String RESPONSETYPE_PKCS7 = "PKCS7";
public static final String RESPONSETYPE_PKCS7WITHCHAIN = "PKCS7WITHCHAIN";
public static final int CERT_REQ_TYPE_PKCS10 = 0;
public static final int CERT_REQ_TYPE_CRMF = 1;
public static final int CERT_REQ_TYPE_SPKAC = 2;
public static final int CERT_REQ_TYPE_PUBLICKEY = 3;
public CertificateHelper() {
}
public static Certificate getCertificate(byte[] certificateData) throws CertificateException {
Certificate retval = CertTools.getCertfromByteArray(Base64.decode(certificateData), Certificate.class);
return retval;
}
public static byte[] getPKCS7(byte[] pkcs7Data) {
return Base64.decode(pkcs7Data);
}
}
on getCertificate() function call another class CertTools function getCertfromByteArray()
public static <T extends Certificate> T getCertfromByteArray(byte[] cert, Class<T> returnType) throws CertificateParsingException {
return getCertfromByteArray(cert, "BC", returnType);
}
and detail function of getCertfromByteArray()
public static <T extends Certificate> T getCertfromByteArray(byte[] cert, String provider, Class<T> returnType) throws CertificateParsingException {
T ret = null;
String prov = provider;
if (provider == null) {
prov = "BC";
}
if (returnType.equals(X509Certificate.class)) {
ret = parseX509Certificate(prov, cert);
} else if (returnType.equals(CardVerifiableCertificate.class)) {
ret = parseCardVerifiableCertificate(prov, cert);
} else {
try {
ret = parseX509Certificate(prov, cert);
} catch (CertificateParsingException var8) {
try {
ret = parseCardVerifiableCertificate(prov, cert);
} catch (CertificateParsingException var7) {
throw new CertificateParsingException("No certificate could be parsed from byte array. See debug logs for details.");
}
}
}
return (Certificate)ret;
}
process on line 779 get log print
process on line 780 can't execution then client get returned response with http code 200
proses on line 781 not execution because on line 780
any suggestion why from line 780 give response to my postman with null body and http code success 200 ?
*Note class CertificateHelper and CertTools is library from official https://mvnrepository.com/artifact/org.ejbca
I'm looking for a way to validate apple's login token.
The validation must be done on backend side so i'm sure that i can add a new account safely.
Onother issue is that i need to convert the key https://appleid.apple.com/auth/keys in xml format to Public Key pem format.
I have found a possible solution that I will post below.
The code is implemented in Java
public static void main(String...args) throws Exception {
String jwtAppleToken = ""; //copy here the token from apple
//copied from https://appleid.apple.com/auth/keys
final String base64UrlEncodedModulus = "lxrwmuYSAsTfn-lUu4goZSXBD9ackM9OJuwUVQHmbZo6GW4Fu_auUdN5zI7Y1dEDfgt7m7QXWbHuMD01HLnD4eRtY-RNwCWdjNfEaY_esUPY3OVMrNDI15Ns13xspWS3q-13kdGv9jHI28P87RvMpjz_JCpQ5IM44oSyRnYtVJO-320SB8E2Bw92pmrenbp67KRUzTEVfGU4-obP5RZ09OxvCr1io4KJvEOjDJuuoClF66AT72WymtoMdwzUmhINjR0XSqK6H0MdWsjw7ysyd_JhmqX5CAaT9Pgi0J8lU_pcl215oANqjy7Ob-VMhug9eGyxAWVfu_1u6QJKePlE-w";
final String base64UrlEncodedExp = "AQAB";
String publicKey = getPemPublicKeyFromBase64UrlEncodedXMLRSAKey(base64UrlEncodedModulus, base64UrlEncodedExp);
System.out.println(verify(jwtAppleToken, publicKey));
System.out.println("-----BEGIN PUBLIC KEY-----");
System.out.println(publicKey);
System.out.println("-----END PUBLIC KEY-----");
}
The same solution with Jose4 lib,
This HttpsJwksVerificationKeyResolver will pick the public key based on key id from the list. so we don't have to deal with it.
import org.jose4j.jwk.HttpsJwks;
import org.jose4j.jwt.JwtClaims;
import org.jose4j.jwt.consumer.JwtConsumer;
import org.jose4j.jwt.consumer.JwtConsumerBuilder;
import org.jose4j.keys.resolvers.HttpsJwksVerificationKeyResolver;
HttpsJwks httpsJkws = new HttpsJwks("https://appleid.apple.com/auth/keys");
HttpsJwksVerificationKeyResolver httpsJwksKeyResolver = new HttpsJwksVerificationKeyResolver(httpsJkws);
JwtConsumer jwtConsumer = new JwtConsumerBuilder()
.setVerificationKeyResolver(httpsJwksKeyResolver)
.setExpectedIssuer("https://appleid.apple.com")
.setExpectedAudience(<clientId>)
.build();
JwtClaims jwtClaims = jwtConsumer.processToClaims(<idToken>);
processToClaims will throw appropriate exceptions, just catch and act accordingly.
Hope this keeps simple and makes more readable for other developers.
This is a possible solution for the validation of the apple login token.
The implementation uses the Apple public key published on --> https://appleid.apple.com/auth/keys
The keys are converted in PEM format from XML format (https://appleid.apple.com/auth/keys) and than the token is validated.
Some of the code can be used to convert modulus and exponent in string format to RSA Public key in PEM Format
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.RsaVerifier;
public class VerifyAppleToken {
public static void main(String...args) throws Exception {
String jwtAppleToken = ""; //copy here the token from apple
System.out.println("THE TOKEN IS VERIFIED FOR ONE OF APPLE KEYS:"+verify(jwtAppleToken));
//copied from https://appleid.apple.com/auth/keys
final String base64UrlEncodedModulus = "lxrwmuYSAsTfn-lUu4goZSXBD9ackM9OJuwUVQHmbZo6GW4Fu_auUdN5zI7Y1dEDfgt7m7QXWbHuMD01HLnD4eRtY-RNwCWdjNfEaY_esUPY3OVMrNDI15Ns13xspWS3q-13kdGv9jHI28P87RvMpjz_JCpQ5IM44oSyRnYtVJO-320SB8E2Bw92pmrenbp67KRUzTEVfGU4-obP5RZ09OxvCr1io4KJvEOjDJuuoClF66AT72WymtoMdwzUmhINjR0XSqK6H0MdWsjw7ysyd_JhmqX5CAaT9Pgi0J8lU_pcl215oANqjy7Ob-VMhug9eGyxAWVfu_1u6QJKePlE-w";
final String base64UrlEncodedExp = "AQAB";
String publicKey = getPemPublicKeyFromBase64UrlEncodedXMLRSAKey(base64UrlEncodedModulus, base64UrlEncodedExp);
System.out.println(verify(jwtAppleToken, publicKey));
//copied from and converted to base64 from base64UrlEncoded https://appleid.apple.com/auth/keys on
// 07/02/2020
final String base64EncodedModulus = "lxrwmuYSAsTfn+lUu4goZSXBD9ackM9OJuwUVQHmbZo6GW4Fu/auUdN5zI7Y1dEDfgt7m7QXWbHuMD01HLnD4eRtY+RNwCWdjNfEaY/esUPY3OVMrNDI15Ns13xspWS3q+13kdGv9jHI28P87RvMpjz/JCpQ5IM44oSyRnYtVJO+320SB8E2Bw92pmrenbp67KRUzTEVfGU4+obP5RZ09OxvCr1io4KJvEOjDJuuoClF66AT72WymtoMdwzUmhINjR0XSqK6H0MdWsjw7ysyd/JhmqX5CAaT9Pgi0J8lU/pcl215oANqjy7Ob+VMhug9eGyxAWVfu/1u6QJKePlE+w==";
final String base64EncodedExp = "AQAB";
System.out.println("-----BEGIN PUBLIC KEY-----");
System.out.println(getPemPublicKeyFromBase64XMLRSAKey(base64EncodedModulus, base64EncodedExp));
System.out.println("-----END PUBLIC KEY-----");
}
private static boolean verify(String jwtAppleToken) throws NoSuchAlgorithmException, InvalidKeySpecException {
AppleKeysRetrieverService retriver = new AppleKeysRetrieverService();
AppleKeysResponse res = retriver.sendRetriveRequest("https://appleid.apple.com/auth/keys");
List<AppleKeyDTO> appleKeys = res.getKeys();
for (AppleKeyDTO appleKeyDTO : appleKeys) {
final String base64UrlEncodedModulus = appleKeyDTO.getN();
final String base64UrlEncodedExp = appleKeyDTO.getE();
String publicKey1 = getPemPublicKeyFromBase64UrlEncodedXMLRSAKey(base64UrlEncodedModulus, base64UrlEncodedExp);
if(verify(jwtAppleToken, publicKey1)) {
return true;
}
}
return false;
}
public static boolean verify(String jwtToken, String publicKey) {
try {
JwtHelper.decodeAndVerify(jwtToken, new RsaVerifier(getRSAPublicKey(publicKey)));
} catch (Exception e) {
return false;
}
return true;
}
private static RSAPublicKey getRSAPublicKey(String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
KeyFactory keyFactory = java.security.KeyFactory.getInstance("RSA");
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(java.util.Base64.getDecoder().decode(publicKey));
return (RSAPublicKey) keyFactory.generatePublic(keySpec);
}
private static String getPemPublicKeyFromBase64UrlEncodedXMLRSAKey(String urlBase64Modulus, String urlBase64Exp) throws NoSuchAlgorithmException, InvalidKeySpecException {
byte[] e = Base64.getUrlDecoder().decode(urlBase64Exp);
byte[] n = Base64.getUrlDecoder().decode(urlBase64Modulus);
BigInteger exponent = new BigInteger(1, e);
BigInteger modulus = new BigInteger(1, n);
return getPemPublicKey(modulus, exponent);
}
private static String getPemPublicKeyFromBase64XMLRSAKey(String base64Modulus, String base64Exp) throws NoSuchAlgorithmException, InvalidKeySpecException {
byte[] e = Base64.getDecoder().decode(base64Exp);
byte[] n = Base64.getDecoder().decode(base64Modulus);
BigInteger exponent = new BigInteger(1, e);
BigInteger modulus = (new BigInteger(1, n));
return getPemPublicKey(modulus, exponent);
}
private static String getPemPublicKey(BigInteger modulus, BigInteger exponent) throws NoSuchAlgorithmException, InvalidKeySpecException {
RSAPublicKeySpec publicKeySpec = new java.security.spec.RSAPublicKeySpec(modulus, exponent);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey myPublicKey = keyFactory.generatePublic(publicKeySpec);
byte[] park = Base64.getEncoder().encode(myPublicKey.getEncoded());
return new String(park);
}
}
RETRIVE APPLE KEYS:
public class AppleKeysRetrieverService {
public AppleKeysResponse sendRetriveRequest(String retriveAppleKeysUrl) {
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters()
.add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8));
String appleKeysResponse = restTemplate
.getForObject(retriveAppleKeysUrl, String.class);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(
DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
AppleKeysResponse res = null;
try {
res = objectMapper.readValue(appleKeysResponse, AppleKeysResponse.class);
return res;
}catch(Exception e) {
return null;
}
}
}
public class AppleKeyDTO {
public String kty;
public String kid;
public String sig;
public String alg;
public String n;
public String e;
public String getKty() {
return kty;
}
public void setKty(String kty) {
this.kty = kty;
}
public String getKid() {
return kid;
}
public void setKid(String kid) {
this.kid = kid;
}
public String getSig() {
return sig;
}
public void setSig(String sig) {
this.sig = sig;
}
public String getAlg() {
return alg;
}
public void setAlg(String alg) {
this.alg = alg;
}
public String getN() {
return n;
}
public void setN(String n) {
this.n = n;
}
public String getE() {
return e;
}
public void setE(String e) {
this.e = e;
}
}
public class AppleKeysResponse {
private List<AppleKeyDTO> keys;
public List<AppleKeyDTO> getKeys() {
return keys;
}
public void setKeys(List<AppleKeyDTO> keys) {
this.keys = keys;
}
}
I am trying to write a program using chronicle map. I have written a UDP server which will broadcast a message every 1 sec. A UDP client will receive the message and will store the message in a chronicle map. The programs are as under:
The UDP server program:
public class UDPServer {
public static void main(String[] args) {
DatagramSocket socket = null;
try {
socket = new DatagramSocket();
byte[] buf = new byte[256];
String messg = "Hello UDP Server\n";
String transmittedMsg = null;
int count = 0;
while (true) {
transmittedMsg = count + "";
buf = transmittedMsg.getBytes();
InetAddress address = InetAddress.getByName ("127.0.0.1");
DatagramPacket packet = new DatagramPacket (buf, buf.length, address, 4000);
socket.send(packet);
Thread.sleep(1000);
count++;
}
} catch (SocketTimeoutException ex) {
System.out.println("Timeout error: " + ex.getMessage());
ex.printStackTrace();
} catch (IOException ex) {
System.out.println("Client error: " + ex.getMessage());
ex.printStackTrace();
} catch (InterruptedException ex) {
ex.printStackTrace();
} finally {
socket.close();
}
}
}
The UDP client program:
public class UDPClient {
public static void main(String[] args) {
DatagramSocket socket = null;
DatagramPacket packet = null;
byte[] buf = new byte[256];
ChronicleMap<String, String> cr = null;
try {
socket = new DatagramSocket(4000);
InetAddress address = InetAddress.getByName ("127.0.0.1");
while (true) {
packet = new DatagramPacket(buf, buf.length, address, 5000);
socket.receive(packet);
String received = new String(packet.getData());
System.out.println(received);
cr = ChronicleMapBuilder.of(String.class, String.class)
.name("test-map")
.averageKey("Message")
.averageValue("0")
.entries(1)
.actualChunkSize(100)
.actualSegments(1)
.createPersistedTo(new File("D://test.txt"));
cr.put("Message", received);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cr != null) {
cr.close();
}
}
}
}
Below is the exception I am geting:
java.lang.IllegalArgumentException: ChronicleMap{name=test-map, file=D:\test.txt, identityHashCode=11583403}: Entry is too large: requires 68 chunks, 9 is maximum.
at net.openhft.chronicle.map.impl.CompiledMapQueryContext.allocReturnCode(CompiledMapQueryContext.java:1805)
at net.openhft.chronicle.map.impl.CompiledMapQueryContext.allocReturnCodeGuarded(CompiledMapQueryContext.java:123)
at net.openhft.chronicle.map.impl.CompiledMapQueryContext.alloc(CompiledMapQueryContext.java:3468)
at net.openhft.chronicle.map.impl.CompiledMapQueryContext.initEntryAndKey(CompiledMapQueryContext.java:3502)
at net.openhft.chronicle.map.impl.CompiledMapQueryContext.putEntry(CompiledMapQueryContext.java:3995)
at net.openhft.chronicle.map.impl.CompiledMapQueryContext.doInsert(CompiledMapQueryContext.java:4184)
at net.openhft.chronicle.map.MapEntryOperations.insert(MapEntryOperations.java:153)
at net.openhft.chronicle.map.impl.CompiledMapQueryContext.insert(CompiledMapQueryContext.java:4107)
at net.openhft.chronicle.map.MapMethods.put(MapMethods.java:88)
at net.openhft.chronicle.map.VanillaChronicleMap.put(VanillaChronicleMap.java:724)
at udp.client.UDPClient.main(UDPClient.java:38)
Please help.
Apparently, some entry that you receive is much larger than
averageKey("Message")
averageValue("0")
That you specified.
You also mix together high-level configurations: averageKey(), averageValue(), entries(), and low-level ones: actualChunkSize(), actualSegments(), that is not recommended.
I am doing performance testing for application which is using Aws cognito login.
Error message
{"__type":"NotAuthorizedException","message":"Incorrect username or password."}
is shown when i rerun the recorded scripts in jmeter. What is the dynamic variable SRP_A which we are passing as the input for the first API call? Passing this variable along with username, Auth flow, client Id gives the challenge parameters.
I have to understand what is SRP_A and how to handle it in jmeter.
SRP_A is a large integer as defined by the Secure Remote Password Protocol. Are you trying to do SRP or just authenticate with username and password. For username/password authentication you should use the AdminInitiateAuth operation.
JMeter provides a facility to manage login and password: CSV Dataset Config. By defining a CSV file containing all the login and password couples, JMeter can pick a line from the file on each user iteration and assign them into variables. This is fairly straightforward, I’m going to explain how:
https://octoperf.com/blog/2017/12/14/multiple-user-login-jmeter/
I don't think Cognito login is something you can record and replay, you need to implement User Pool Authentication Flow manually.
With regards to Cognito the easiest way is using AWS Java SDK from JSR223 Test Elements using Groovy language
Example helper class for getting SRP_A value out of the username:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.math.pro.ak.util.cognito
import com.amazonaws.AmazonClientException
import com.amazonaws.util.StringUtils
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.security.SecureRandom
/**
*
* #author marcus
*/
public class AuthenticationHelper {
private BigInteger a;
private BigInteger A;
private String poolName;
public AuthenticationHelper(String userPoolName) {
do {
a = new BigInteger(EPHEMERAL_KEY_LENGTH, SECURE_RANDOM).mod(N);
A = GG.modPow(a, N);
}
while (A.mod(N).equals(BigInteger.ZERO));
if (userPoolName.contains("_")) {
poolName = userPoolName.split("_", 2)[1];
} else {
poolName = userPoolName;
}
}
public BigInteger geta() {
return a;
}
public BigInteger getA() {
return A;
}
private static final String HEX_N = "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
+ "29024E088A67CC74020BBEA63B139B22514A08798E3404DD"
+ "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
+ "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
+ "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
+ "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
+ "83655D23DCA3AD961C62F356208552BB9ED529077096966D"
+ "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B"
+ "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9"
+ "DE2BCBF6955817183995497CEA956AE515D2261898FA0510"
+ "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64"
+ "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7"
+ "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B"
+ "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C"
+ "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31"
+ "43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF";
private static final BigInteger N = new BigInteger(HEX_N, 16);
private static final BigInteger GG = BigInteger.valueOf(2);
private static final BigInteger KK;
private static final int EPHEMERAL_KEY_LENGTH = 1024;
private static final int DERIVED_KEY_SIZE = 16;
private static final String DERIVED_KEY_INFO = "Caldera Derived Key";
private static final ThreadLocal<MessageDigest> THREAD_MESSAGE_DIGEST = new ThreadLocal<MessageDigest>() {
#Override
protected MessageDigest initialValue() {
try {
return MessageDigest.getInstance("SHA-256");
} catch (final NoSuchAlgorithmException e) {
throw new AmazonClientException("Exception in authentication", e);
}
}
};
private static final SecureRandom SECURE_RANDOM;
static {
try {
SECURE_RANDOM = SecureRandom.getInstance("SHA1PRNG");
final MessageDigest messageDigest = THREAD_MESSAGE_DIGEST.get();
messageDigest.reset();
messageDigest.update(N.toByteArray());
final byte[] digest = messageDigest.digest(GG.toByteArray());
KK = new BigInteger(1, digest);
} catch (final NoSuchAlgorithmException e) {
throw new AmazonClientException(e.getMessage(), e);
}
}
public byte[] getPasswordAuthenticationKey(String userId,
String userPassword,
BigInteger B,
BigInteger salt) {
// Authenticate the password
// u = H(A, B)
final MessageDigest messageDigest = THREAD_MESSAGE_DIGEST.get();
messageDigest.reset();
messageDigest.update(A.toByteArray());
final BigInteger u = new BigInteger(1, messageDigest.digest(B.toByteArray()));
if (u.equals(BigInteger.ZERO)) {
throw new AmazonClientException("Hash of A and B cannot be zero");
}
// x = H(salt | H(poolName | userId | ":" | password))
messageDigest.reset();
messageDigest.update(poolName.getBytes(StringUtils.UTF8));
messageDigest.update(userId.getBytes(StringUtils.UTF8));
messageDigest.update(":".getBytes(StringUtils.UTF8));
final byte[] userIdHash = messageDigest.digest(userPassword.getBytes(StringUtils.UTF8));
messageDigest.reset();
messageDigest.update(salt.toByteArray());
final BigInteger x = new BigInteger(1, messageDigest.digest(userIdHash));
final BigInteger s = (B.subtract(KK.multiply(GG.modPow(x, N)))
.modPow(a.add(u.multiply(x)), N)).mod(N);
Hkdf hkdf = null;
try {
hkdf = Hkdf.getInstance("HmacSHA256");
} catch (final NoSuchAlgorithmException e) {
throw new AmazonClientException(e.getMessage(), e);
}
hkdf.init(s.toByteArray(), u.toByteArray());
final byte[] key = hkdf.deriveKey(DERIVED_KEY_INFO, DERIVED_KEY_SIZE);
return key;
}
}
I have been following this post on how to create an entry point into my spring mvc 3.1 web application for someone to login using a json request.
Spring Security and JSON Authentication
I've got a question about the code below. Inside attemptAuthentication I am adding extra request parameters which are json specific. And then I try to access those parameters in obtainUsername and obtainPassword but the parameters are not there.
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException {
if ("application/json".equals(request.getHeader("Content-Type"))) {
StringBuffer sb = new StringBuffer();
String line = null;
BufferedReader reader;
try {
reader = request.getReader();
while ((line = reader.readLine()) != null){
sb.append(line);
}
//json transformation
ObjectMapper mapper = new ObjectMapper();
JsonLoginRequest loginRequest = mapper.readValue(sb.toString(), JsonLoginRequest.class);
String jsonUsername = loginRequest.getJ_username();
request.setAttribute("jsonUsername", jsonUsername);
String jsonPassword = loginRequest.getJ_password();
request.setAttribute("jsonPassword", jsonPassword);
String jsonStore = loginRequest.getJ_store();
request.setAttribute("jsonStore", jsonStore);
}
catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
String usernameParameter = obtainUsername(request);
String password = obtainPassword(request);
When I do this jsonUsername and jsonStore don't exist even though I added them above.
#Override
protected String obtainUsername(HttpServletRequest request) {
String combinedUsername = null;
if ("application/json".equals(request.getHeader("Content-Type"))) {
String jsonUsername = request.getParameter("jsonUsername");
String jsonStore = request.getParameter("jsonStore");
combinedUsername =
jsonUsername +
SecurityConstants.TWO_FACTOR_AUTHENTICTION_DELIM +
jsonStore;
}else {
String username = super.obtainUsername(request);
String store = request.getParameter(SecurityConstants.STORE_PARAM);
String hiddenStore = request.getParameter(SecurityConstants.HIDDEN_STORE_PARAM);
combinedUsername =
username +
SecurityConstants.TWO_FACTOR_AUTHENTICTION_DELIM +
store +
SecurityConstants.TWO_FACTOR_AUTHENTICTION_DELIM +
hiddenStore;
}
return combinedUsername;
}
Can someone help me with what is wrong? thanks