I am trying to validate JWT Access token which generated by KeyCloak Authorization server.
I have copied public_key from
http://ip-address:port/auth/realms/
For validating Access token i am using https://mvnrepository.com/artifact/com.auth0/java-jwt
and referring https://www.baeldung.com/java-jwt-token-decode for verifying signature.
Code I am trying:
String publicKey =<public_key from http://<ip>:<port>/auth/realms/<app> >
String accessToken =<valid access token from keycloak>
String[] chunks = accessToken.split("\\.");
Base64.Decoder decoder = Base64.getDecoder();
String header = new String(decoder.decode(chunks[0])); // {"alg":"RS256","typ" : "JWT","kid" : "dsssdssdf"}
String payload = new String(decoder.decode(chunks[1])); //{"exp":1632237161,"iat":1632236861,"auth_time":1632236854,"jt..."}
String signature = chunks[2]; // <signature from access token>
SignatureAlgorithm sa = SignatureAlgorithm.RS256;
String tokenWithoutSignature = chunks[0] + "." + chunks[1];
SecretKeySpec secretKeySpec = new SecretKeySpec(publicKey.getBytes(), sa.getJcaName());
DefaultJwtSignatureValidator validator = new DefaultJwtSignatureValidator(sa, secretKeySpec);
if (!validator.isValid(tokenWithoutSignature, signature)) {
System.out.println("=============== Invalid access token");
} else {
System.out.println("============= valid access token");
}
After running above code following error observed:
java.lang.IllegalArgumentException: RSA Signature validation requires either a RSAPublicKey or RSAPrivateKey instance.
at io.jsonwebtoken.lang.Assert.isTrue(Assert.java:38)
at io.jsonwebtoken.impl.crypto.RsaSignatureValidator.<init>(RsaSignatureValidator.java:36)
at io.jsonwebtoken.impl.crypto.DefaultSignatureValidatorFactory.createSignatureValidator(DefaultSignatureValidatorFactory.java:43)
at io.jsonwebtoken.impl.crypto.DefaultJwtSignatureValidator.<init>(DefaultJwtSignatureValidator.java:37)
at io.jsonwebtoken.impl.crypto.DefaultJwtSignatureValidator.<init>(DefaultJwtSignatureValidator.java:32)
Can anyone please help here?
I try something like :
String publicKey =<public_key from http://<ip>:<port>/auth/realms/<app> >
byte[] decoded = Base64.getDecoder().decode(publicKey);
String algorithm = "RSA";
KeyFactory kf = KeyFactory.getInstance(algorithm);
PublicKey generatedPublic = kf.generatePublic(new X509EncodedKeySpec(decoded));
String accessToken =<valid access token from keycloak>
String[] chunks = accessToken.split("\\.");
Base64.Decoder decoder = Base64.getDecoder();
String header = new String(decoder.decode(chunks[0])); // {"alg":"RS256","typ" : "JWT","kid" : "dsssdssdf"}
String payload = new String(decoder.decode(chunks[1])); //{"exp":1632237161,"iat":1632236861,"auth_time":1632236854,"jt..."}
String signature = chunks[2]; // <signature from access token>
SignatureAlgorithm sa = SignatureAlgorithm.RS256;
String tokenWithoutSignature = chunks[0] + "." + chunks[1];
DefaultJwtSignatureValidator validator = new DefaultJwtSignatureValidator(sa, generatedPublic);
if (!validator.isValid(tokenWithoutSignature, signature)) {
System.out.println("=============== Invalid access token");
} else {
System.out.println("============= valid access token");
}
and It worked !!
Related
I need some help with JWS Signing with RSA 256 privatekey -RSASSA-PKCS1-v1.5 SHA-256
I m working on SAP PI/PO.
I am unable to retrieve the RSA privatekey saved in server's OS folder, so I am trying to pass the pem(base64 encoded) key as a string.
My requirement is to generate Header & payload & signed it.
Sample input Header:
{"alg": "RS256","kid": "asff1233dd"}
sample Json Payload:
{"CompInvoiceId": "0009699521","IssueDtm": "20220623"}<br />
Error: I am able to generate Header.payload in base64 url encode but the signature part is getting corrupted when I convert the privatekey to PKCS8encoding.
The generated JWS looks like:
eyJhbGciOiJSUzI1NiIsImtpZCI6Imh5d3kzaHIifQ.eyJDb21waW52b2ljZSI6IjAwOTk5MzMzIiwic3VibWl0SWQiOiIxMjM0NSJ9.[B#42ace6ba
This is signature part which is getting corrupted - [B#42ace6ba
Kindly help with below code:
This is because of this declaration byte[] signed = null, when I remove
that it just throwserror as cannot find variable for signed.
Please help me with passing privatekey & signature.
The Java code I am working on:
I am passing :
Json data= data,
header = header
Privatekey in base64 = key
String jwsToken(String key, String data, String header, Container container) throws
StreamTransformationException{
String tok = null;
byte[] signed = null;
try {
StringBuffer token = new StringBuffer();
//Encode the JWT Header and add it to our string to sign
token.append(Base64.getUrlEncoder().withoutPadding().encodeToString(header.getBytes("UTF-
8")));
token.append(".");
//Encode the Json payload
token.append(Base64.getUrlEncoder().withoutPadding().encodeToString(data.getBytes("UTF-8")));
//Separate with a period
token.append(".");
//String signedPayload =
Base64.getUrlEncoder().withoutPadding().encodeToString(signature.sign());
PrivateKey privatekey = null;
String privateKeyPEM = key;
//String key = new String(Files.readAllBytes(file.toPath()), Charset.defaultCharset());
byte[] decodePrivateKey = Base64.getDecoder().decode(key);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodePrivateKey);
privatekey = (PrivateKey) keyFactory.generatePrivate(keySpec);
Signature sig = Signature.getInstance( "SHA256withRSA" );
sig.initSign( ( PrivateKey ) privatekey );
sig.update(token.toString().getBytes("UTF-8"));
signed=sig.sign();
tok = (token.toString());
}
catch (Exception e) {
e.printStackTrace();
}
return tok;
}
Instead of appending byte array, encode it in base64 then append it
signed = sig.sign();
token.append(Base64.getUrlEncoder().withoutPadding().encodeToString(signed));
Now I want to generate an JWT token to request apple server follow this docs, I have the p8 file download from apple, how to get jwt sign key from p8 file? this is my jwt token generate code:
Map<String,Object> jwtHeader = new HashMap<>();
jwtHeader.put("alg","ES256");
jwtHeader.put("kid","YDKL424AF9");
jwtHeader.put("typ","JWT");
Map<String,Object> appleJwtPayload = new HashMap<>();
appleJwtPayload.put("iss","5fb8e836-27d7-4390-8f40-008acd64a29d");
appleJwtPayload.put("iat",System.currentTimeMillis() / 1000L);
appleJwtPayload.put("exp",System.currentTimeMillis() / 1000L + 60 * 15);
appleJwtPayload.put("aud","appstoreconnect-v1");
appleJwtPayload.put("nonce",UUID.randomUUID().toString());
appleJwtPayload.put("bid","com.earth.dolphin");
String appleKey = "<how to get the apple key>";
SecretKey secretKey = new SecretKeySpec(appleKey.getBytes(), SignatureAlgorithm.ES256.getJcaName());
String accessToken = Jwts.builder()
.setClaims(appleJwtPayload)
.setHeader(jwtHeader)
.signWith(secretKey)
.compact();
I read the KeyStore code follow this question, but I still could not figure out how to do it, any one could help me?
get the sign key like this:
byte[] p8der = Files.readAllBytes(Path.of("/opt/apps/dolphin-post/AuthKey_YDKL424AF9.p8"));
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(new org.apache.commons.codec.binary.Base64().decode(p8der));
PrivateKey appleKey = KeyFactory.getInstance("EC").generatePrivate(priPKCS8);
the file AuthKey_YDKL424AF9.p8 was download from apple, you should remove the begin and end header of the file. This is my full function to get private key:
public static PrivateKey getPrivateKey(String filename, String algorithm) throws IOException {
String content = new String(Files.readAllBytes(Paths.get(filename)), "utf-8");
try {
String privateKey = content.replace("-----BEGIN PRIVATE KEY-----", "")
.replace("-----END PRIVATE KEY-----", "")
.replaceAll("\\s+", "");
KeyFactory kf = KeyFactory.getInstance(algorithm);
return kf.generatePrivate(new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey)));
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Java did not support the algorithm:" + algorithm, e);
} catch (InvalidKeySpecException e) {
throw new RuntimeException("Invalid key format");
}
}
you can use it like this:
PrivateKey appleKey = SecurityUtil.getPrivateKey(APPLE_PRIVATE_KEY_PATH,"EC");
the APPLE_PRIVATE_KEY_PATH in my OS is:
apple.private.key.path=/opt/apps/dolphin-post/AuthKey.p8
changed it to your path.
I have a PrivateKey and a PublicKey and use the privateKey to init Signature and publicKey to verify the Signature:
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
// decode public key
X509EncodedKeySpec publicSpec = new X509EncodedKeySpec(pubKeyBytes);
RSAPublicKey pubKey = (RSAPublicKey)
keyFactory.generatePublic(publicSpec);
//decode private key
PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(prvKeyBytes);
RSAPrivateKey privKey = (RSAPrivateKey)
keyFactory.generatePrivate(privSpec);
//header and body Base64 decoded value
String headerString = mapper.writeValueAsString(header);
String headerEncoded =
Base64.getUrlEncoder().encodeToString(headerString.getBytes());
String payloadString = mapper.writeValueAsString(payload);
String payloadEncoded =
Base64.getUrlEncoder().encodeToString(payloadString.getBytes());
String tempAccessToken = hearderEncoded+"."+payloadString;
Signature sign = Signature.getInstance("SHA256withRSA");
sign.initSign(privKey);
sign.update(tempAccessToken.getBytes("UTF-8"));
byte[] signatureBytes = sign.sign();
sign.initVerify(pubKey);
sign.update(tempAccessToken.getBytes("UTF-8"));
String jsonToken = Base64.getUrlEncoder().encodeToString(signatureBytes);
String JWTtoken = tempAccessToken + "." + jsonToken;
finally I get the JWT token below (dummy value):
eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiI4MzliN2NhNC02MDE1LTQ0OWQtOGZiNi02jkyYzk1Ny1jYTNjLTQyMWQtOTk2zY2VkNTAzZGViNWYiLCJleHAiOjE1MzIwMDQwMTcsImF1ZCI6ImFjY291bnQtZC5kb2N1c2lnbi5jb20iLzY29wZSI6InNpZ25hdHVyZSBpbXBlcnNvbmF0aW9uIn0=.YNZzR0HgPWFm4dXMMHn3czEDRukYUB0Hyw7YP_BGY2dniIMqpH4Ctz5EEHcHrNT_mGImcp026w-isYgv56TTugYnkcAs8HH0YXa1Ey0skdjVYoZHdeyPC8Ci9xeOQF9wf4VjrBboaRxWkVXfngOHHewpV42NcaXxwmGlresWukHVmmjbFokd1Cm5BJKVhVlsZWuftcJlC3XoO9REjaZX78YTY9S5bpXmsZBYr20wHsWJrkP9EWGf7WSGHVXGBJfCpvOTZDC8_4B12ToD_RKjk6n5s8-F7X54KY4kx6Gg7xnk55vDw==
I'm not able to get the accessToken using this JWT Token. I will get the response instead:
"error" :"invalid_request";
NOTE: I am using this JWT token to get the access token for DocuSign Application.
I am looking to develop a JWT app with RSA encryption using "Nimbus JOSE+JWT" library. I am seeking sample code.
I would like to use the following Maven dependency:
<dependency>
<groupId>com.nimbusds</groupId>
<artifactId>nimbus-jose-jwt</artifactId>
<version>3.10</version>
</dependency>
Note: Please always use the latest version from Maven Central repository.
If you're using the latest version of 4.23 of 'Nimbus Jose JWT' then there is some minor changes in the API.
<dependency>
<groupId>com.nimbusds</groupId>
<artifactId>nimbus-jose-jwt</artifactId>
<version>4.23</version>
</dependency>
I've shown the code below for reference:
public class JwtJoseExample {
public static void main(String[] args) {
KeyPairGenerator keyPairGenerator;
try {
keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024);
// generate the key pair
KeyPair keyPair = keyPairGenerator.genKeyPair();
// create KeyFactory and RSA Keys Specs
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPublicKeySpec publicKeySpec = keyFactory.getKeySpec(keyPair.getPublic(), RSAPublicKeySpec.class);
RSAPrivateKeySpec privateKeySpec = keyFactory.getKeySpec(keyPair.getPrivate(), RSAPrivateKeySpec.class);
// generate (and retrieve) RSA Keys from the KeyFactory using Keys Specs
RSAPublicKey publicRsaKey = (RSAPublicKey) keyFactory.generatePublic(publicKeySpec);
RSAPrivateKey privateRsaKey = (RSAPrivateKey) keyFactory.generatePrivate(privateKeySpec);
JWTClaimsSet.Builder claimsSet = new JWTClaimsSet.Builder();
claimsSet.issuer("https://my-auth-server.com");
claimsSet.subject("John Kerr");
claimsSet.audience(getAudience());
claimsSet.expirationTime(new Date(new Date().getTime() + 1000*60*10));
claimsSet.notBeforeTime(new Date());
claimsSet.jwtID(UUID.randomUUID().toString());
System.out.println("--------------------------");
System.out.println("Claim Set : \n"+claimsSet.build());
// create the JWT header and specify:
// RSA-OAEP as the encryption algorithm
// 128-bit AES/GCM as the encryption method
JWEHeader header = new JWEHeader(JWEAlgorithm.RSA_OAEP, EncryptionMethod.A128GCM);
// create the EncryptedJWT object
EncryptedJWT jwt = new EncryptedJWT(header, claimsSet.build());
// create an RSA encrypter with the specified public RSA key
RSAEncrypter encrypter = new RSAEncrypter(publicRsaKey);
// do the actual encryption
jwt.encrypt(encrypter);
// serialize to JWT compact form
String jwtString = jwt.serialize();
System.out.println("\nJwt Compact Form : "+jwtString);
// in order to read back the data from the token using your private RSA key:
// parse the JWT text string using EncryptedJWT object
jwt = EncryptedJWT.parse(jwtString);
// create a decrypter with the specified private RSA key
RSADecrypter decrypter = new RSADecrypter(privateRsaKey);
// do the decryption
jwt.decrypt(decrypter);
// print out the claims
System.out.println("===========================================================");
System.out.println("Issuer: [ " + jwt.getJWTClaimsSet().getIssuer() + "]");
System.out.println("Subject: [" + jwt.getJWTClaimsSet().getSubject()+ "]");
System.out.println("Audience size: [" + jwt.getJWTClaimsSet().getAudience().size()+ "]");
System.out.println("Expiration Time: [" + jwt.getJWTClaimsSet().getExpirationTime()+ "]");
System.out.println("Not Before Time: [" + jwt.getJWTClaimsSet().getNotBeforeTime()+ "]");
System.out.println("Issue At: [" + jwt.getJWTClaimsSet().getIssueTime()+ "]");
System.out.println("JWT ID: [" + jwt.getJWTClaimsSet().getJWTID()+ "]");
System.out.println("===========================================================");
} catch (NoSuchAlgorithmException | InvalidKeySpecException | JOSEException | ParseException e) {
System.out.println(e.getMessage());
}
}
private static List<String> getAudience(){
List<String> audience = new ArrayList<>();
audience.add("https://my-web-app.com");
audience.add("https://your-web-app.com");
return audience;
}
}
The output is:
Claim Set :
{"sub":"John Kerr","aud":["https:\/\/my-web-app.com","https:\/\/your-web-app.com"],"nbf":1471116052,"iss":"https:\/\/my-auth-server.com","exp":1471116652,"jti":"8769fc6d-b69f-45e3-b1a5-52695c23675e"}
Jwt Compact Form :
eyJlbmMiOiJBMTI4R0NNIiwiYWxnIjoiUlNBLU9BRVAifQ.f2ZZyMaJi03RqunyWsLvIr7tNX1KvTRUcpN9qsBHvbXIouZCyepQMsbI1v88GHuLIV3f6SviCDyICp7kZCj_9q-yIi_dIuroADWQ-P_UnqNPRXQ1yEwbmrLUK80lBtKyc3Z6g_3Db_HLtD6QPEq-zUAh3wJ7uSPxhql2oc9otGc.Xbyrf4iWM0shNp4S.TCKoJGAEQ4rpJJk2qZP11awxTEWTg-r5VpppGgZNhiHCBhnGnyR2sb86O7ISc3j-i4OYp7Xl2vThzztD1ojy_IKPYQkg_iACuo6yjzdopQQT143vjYuFLfFhQFfjfCoO6iibTqK7vmqfF0bUWD6Nj-4MwjlW6dFV7mNQEN50dkiMrFMZkmiVKZRa50jOK1NcoWYiKSrCOQduJYibJfF6jSQARX9MsX5tib-3BXSsKtPLNrQ6mFfvDzzruBuO4gKWLE3PQPUfIQ.gXt5KcpxEbfYLP854GvcQw
===========================================================
Issuer: [ https://my-auth-server.com]
Subject: [John Kerr]
Audience size: [2]
Expiration Time: [Sun Aug 14 01:00:52 IST 2016]
Not Before Time: [Sun Aug 14 00:50:52 IST 2016]
Issue At: [null]
JWT ID: [8769fc6d-b69f-45e3-b1a5-52695c23675e]
===========================================================
//This is a complete encryption and decryption module using
//Algorithm: JWEAlgorithm.RSA_OAEP_256
//Encryption Method: A128CBC_HS256
public static String encrypt(String text) throws Exception {
// Set the plain text
Payload payload = new Payload(text);
// Create the header
JWEHeader header = new JWEHeader(JWEAlgorithm.RSA_OAEP_256, EncryptionMethod.A128CBC_HS256);
// Create the JWE object and encrypt it
JWEObject jweObject = new JWEObject(header, payload);
jweObject.encrypt(new RSAEncrypter(getPublicKey()));
// Serialise to compact JOSE form...
String jweString = jweObject.serialize();
LOG.info("Generated Encrypted Key : {}", jweString);
return jweString;
}
public static String decrypt(String text) throws Exception {
// Parse into JWE object...
JWEObject jweObject = JWEObject.parse(text);
jweObject.decrypt(new RSADecrypter(getPrivateKey()));
// Get the plain text
Payload payload = jweObject.getPayload();
System.out.println(payload.toString());
return payload.toString();
}
private static RSAPublicKey getPublicKey() throws Exception {
String filename = "/home/vaibhav/Setups/cert/pub.der";
File f = new File(filename);
FileInputStream fis = new FileInputStream(f);
DataInputStream dis = new DataInputStream(fis);
byte[] keyBytes = new byte[(int)f.length()];
dis.readFully(keyBytes);
dis.close();
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
return (RSAPublicKey) kf.generatePublic(spec);
}
private static RSAPrivateKey getPrivateKey() throws Exception {
String filename = "/home/vaibhav/Setups/cert/private.pkcs8";
File f = new File(filename);
FileInputStream fis = new FileInputStream(f);
DataInputStream dis = new DataInputStream(fis);
byte[] keyBytes = new byte[(int)f.length()];
dis.readFully(keyBytes);
dis.close();
PKCS8EncodedKeySpec spec1 = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
return (RSAPrivateKey) kf.generatePrivate(spec1);
}
I implemented the code to use "nimbus-jose-jwt" library, please find the code below
JWTClaimsSet jwtClaims = new JWTClaimsSet();
jwtClaims.setIssuer(ISSUER);
jwtClaims.setSubject(SUBJECT);
List<String> aud = new ArrayList<String>();
aud.add("https://app-one.com");
aud.add("https://app-two.com");
jwtClaims.setAudience(aud);
// Set expiration in 10 minutes
jwtClaims.setExpirationTime(new Date(new Date().getTime() + 1000*60*10));
jwtClaims.setNotBeforeTime(new Date());
jwtClaims.setIssueTime(new Date());
jwtClaims.setJWTID(UUID.randomUUID().toString());
System.out.println("=========== JWT CLAMINS =============");
System.out.println(jwtClaims.toJSONObject());
// Request JWT encrypted with RSA-OAEP and 128-bit AES/GCM
JWEHeader header = new JWEHeader(JWEAlgorithm.RSA_OAEP, EncryptionMethod.A128GCM);
// Create the encrypted JWT object
EncryptedJWT jwt = new EncryptedJWT(header, jwtClaims);
// Create an encrypter with the specified public RSA key
RSAEncrypter encrypter = new RSAEncrypter(publicKey);
jwt.encrypt(encrypter);
String jwtString = jwt.serialize();
System.out.println(jwtString);
// Parse back
jwt = EncryptedJWT.parse(jwtString);
// Create a decrypter with the specified private RSA key
RSADecrypter decrypter = new RSADecrypter(privateKey);
// Decrypt
jwt.decrypt(decrypter);
// Retrieve JWT claims
System.out.println(jwt.getJWTClaimsSet().getIssuer());;
System.out.println(jwt.getJWTClaimsSet().getSubject());
System.out.println(jwt.getJWTClaimsSet().getAudience().size());
System.out.println(jwt.getJWTClaimsSet().getExpirationTime());
System.out.println(jwt.getJWTClaimsSet().getNotBeforeTime());
System.out.println(jwt.getJWTClaimsSet().getIssueTime());
System.out.println(jwt.getJWTClaimsSet().getJWTID());
This code has also use the public and private keys to create JWT token, also you will need those keys to extract claims and validate it.
Once you run this code, you should be able to see following jwtClaims:
{
"exp": 1429126207,
"sub": "alice",
"nbf": 1429125607,
"aud": [
"https://app-one.com",
"https://app-two.com"
],
"iss": "A FaceBook Cooperation",
"jti": "5c94d2db-e818-4746-b2f2-a4cd084d5a44",
"iat": 1429125607
}
guy's, pleeaseee help me!!!
I created a web service which use UserNameToken Profile security with Password type like 'digest'. When i try to use the webservice from SOAP-UI (sending the information in the head of the xml) i can consume the webservice normally, but when i'm trying consume this webservice with JAVA the server don't authenticate the user.
I try to use axis and JAX-WS (send the information in the head of the envelop - like SOAP-UI) but the server don't authenticate the user.
Can someone help me?
Here is my code:
public void faz() throws NoSuchAlgorithmException, Exception {
/////////////////////////////////////////////////////////////
//get the timestamp, nonce and password in SHA-1 and BASE64//
/////////////////////////////////////////////////////////////
String nonce, timestamp, secret;
nonce = String.valueOf(this.hashCode());
BASE64Encoder encoder2 = new BASE64Encoder();
nonce = encoder2.encode(nonce.getBytes());
Calendar c = Calendar.getInstance();
c.setTime(new Date());
timestamp = DatatypeConverter.printDateTime(c);
timestamp = timestamp.substring(0, 19);
timestamp = timestamp+"Z";
secret = "weblogic1";
MessageDigest SHA1 = null;
try {
SHA1 = MessageDigest.getInstance("SHA1");
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
;
String beforeEncryption = nonce + timestamp + secret;
try {
SHA1.reset();
byte[] toEncrypt = beforeEncryption.getBytes("UTF-8");
SHA1.update(beforeEncryption.getBytes());
} catch (UnsupportedEncodingException uee) {
throw new RuntimeException(uee);
}
byte[] encryptedRaw = SHA1.digest();
byte[] encoded = Base64.encodeBase64(encryptedRaw);
MessageDigest digest = MessageDigest.getInstance("SHA-1");
digest.update("password".getBytes());
BASE64Encoder encoder = new BASE64Encoder();
String senha = encoder.encode(digest.digest());
System.err.println(senha);
////////////////////////////////////
//////////END //////////////////////
////////////////////////////////////
CalculaServiceService ss = new CalculaServiceServiceLocator();
CalculaService service = ss.getCalculaServicePort();
String uri = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
String uriCrea = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd";
SOAPHeaderElement securityE = new SOAPHeaderElement(uri, "Security",
null);
SOAPHeaderElement tokenE = new SOAPHeaderElement(uri, "UsernameToken",
null);
SOAPHeaderElement userE = new SOAPHeaderElement(uri, "Username", null);
tokenE.setObjectValue(null);
securityE.setObjectValue(null);
userE.setValue("username");
SOAPHeaderElement pwdE = new SOAPHeaderElement(uri, "Password", null);
pwdE.addAttribute(uri, "Type", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest");
pwdE.setValue(senha);
SOAPHeaderElement nonceE = new SOAPHeaderElement(uri, "Nonce", null);
nonceE.addAttribute(uri, "EncodingType", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest");
nonceE.setValue(nonce);
SOAPHeaderElement createdE = new SOAPHeaderElement(uriCrea, "Created", null);
createdE.setValue(timestamp);
tokenE.addChildElement(userE);
tokenE.addChildElement(pwdE);
tokenE.addChildElement(nonceE);
tokenE.addChildElement(createdE);
securityE.addChildElement(tokenE);
((Stub) service).setHeader(securityE);
service.calcula(13, 10, "somar");
}
WS-Security standard defines the password digest as Base64 ( SHA-1 ( nonce + created + password ) ).
You reflect this correctly by hashing the content of beforeEncryption variable and store the result to encryptedRaw and then base64-encode it to encoded variable. So far so good. But the encoded variable is not used anywhere. For some reason, you compute a second digest base64(sha1("password")) and store it to senha variable that is used later to fill the WSS Password element.
Completely remove the code that computes the second digest and use the content of the encoded variable:
Conceptually, change the pwd.setValue() from:
pwdE.setValue(senha)
To:
pwdE.setValue(encoded)
and make sure that encoded variable will be a String, not a byte array.
Additionally, you should consider to use a better value for nonce than an object hash-code.