Java: Cannot return variable outside of try? - java

I keep getting the following error from the code below
error:
AccountController.java:55: error: cannot find symbol
return encoded;
^
symbol: variable encoded
location: class AccountController
1 error
code:
public static String hash(String password) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] byteOfTextToHash = password.getBytes(StandardCharsets.UTF_8);
byte[] hashedByetArray = digest.digest(byteOfTextToHash);
String encoded;
encoded = Base64.getEncoder().encodeToString(hashedByetArray);
} catch(NoSuchAlgorithmException e) {
e.printStackTrace();
};
return encoded;
}
Thanks for the help!

Your encoded variable is out of scope. Move it outside the try will fix this like:
public static String hash(String password) {
String encoded = null;
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] byteOfTextToHash = password.getBytes(StandardCharsets.UTF_8);
byte[] hashedByetArray = digest.digest(byteOfTextToHash);
encoded = Base64.getEncoder().encodeToString(hashedByetArray);
} catch(NoSuchAlgorithmException e) {
e.printStackTrace();
};
return encoded;
}

Declare the varibale encoded outside try and initialize it with null or empty string as below
String encoded = "";
try {
....
}catch(Exception exc):\{
....
}
return encoded
;

Related

Porting python PKCS1_v1_5 encryption code to java generating different signatures

I am trying to port my working python code for generating signature to java but they both are producing different signatures. Here is my code for python which is generating the signature.
import pdb
pdb.set_trace()
signer = PKCS1_v1_5.new(priv_key)
digest = SHA256.new()
digest.update(message)
val = signer.sign(digest)
return val
I am calling this function using this statement
signature = b64encode(sign(msg1, private))
Here the msg1 is
msg1 = 'test'.encode("utf8")
and private is the private key which I am importing using
RSA.importKey("<Location of key>"
I am trying to write a similar java code for implementing the same functionality with this given code
public static void main(String[] args) throws Exception {
String payload = "test";
String dig = makeDigest( payload, "SHA-256");
Key k = getPrivateKey("private_key.der");
String signature = encrypt(dig, "RSA", k);
System.out.print(signature);
}
public static String makeDigest(String payload, String digestAlgo) {
String strDigest = "";
try {
MessageDigest md = MessageDigest.getInstance(digestAlgo);
byte[] p_b = payload.getBytes("UTF-8");
md.update(p_b);
byte[] digest = md.digest();
char[] encoded = Hex.encodeHex(digest);
strDigest = new String(encoded);
System.out.println(strDigest);
}
catch (Exception ex) {
ex.printStackTrace();
}
return strDigest;
}
public static String encrypt(String sha, String encryptAlgo, Key k) {
String strEncrypted = "";
try {
Security.addProvider(new BouncyCastleProvider());
Cipher cipher = Cipher.getInstance(encryptAlgo,"BC");
cipher.init(Cipher.ENCRYPT_MODE, k);
byte[] encrypted = cipher.doFinal(sha.getBytes("UTF-8"));
//System.out.println(new String(encrypted));
byte[] encoded = Base64.getEncoder().encode(encrypted);
strEncrypted = new String(encoded);
}
catch (Exception ex) {
ex.printStackTrace();
}
return strEncrypted;
}
public static PrivateKey getPrivateKey(String filename)
throws Exception {
byte[] keyBytes = Files.readAllBytes(Paths.get(filename));
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
Security.addProvider(new BouncyCastleProvider());
KeyFactory kf = KeyFactory.getInstance("RSA","BC");
return kf.generatePrivate(spec);
}
Both thee codes are generating different signatures. I feel something I am doing wrong in selecting the algorithm on Java side. I have tried with
RSA/NONE/PKCS1Padding
and
RSA/ECB/PKCS1Padding
but still, it is different signature as compared to python code.
Any lead on this will be very helpful.

Decode koi8-r string and quoted-printable in java

I got a .eml file, and some attachments inside
one of attachments - is .rar file
I using Tika to extract this rar, but sometimes Tika cant correctly convert some names of files, for example - such a name
=?koi8-r?Q?6=5F=F4=ED=5F15=2E05=2Erar?=
So i was looking for an answer, how to convert such a string to correctly readed value
Is there any libraries in java, to do this?
I guess it happends cause string got =?koi8-r?Q? in the start, so maybe, if i convert string to something like this, i will get move convertable value, like this 6=5F=F4=ED=5F15=2E05=2E, but if i will do so, i finnaly couldnt find a solution to convert
Does anybody know how to convert such a string correctly?
I spend a lot of time to make it, but still - no results...
Here is a code
public class EncodingUtils {
private EncodingUtils() {
}
public static String decodeKoi8r(String text) {
String decode;
try {
decode = MimeUtility.decodeText(text);
} catch (UnsupportedEncodingException e) {
decode = text;
}
if (isQuotedKoi8r(decode)) {
decode = decode(text, "KOI8-R", "quoted-printable", "KOI8-R");
}
return decode;
}
public static boolean isQuotedKoi8r(String text) {
return text.contains("=") || text.toLowerCase().contains("koi8-r");
}
public static String decode(String text, String textEncoding, String encoding, String resultCharset) {
if (text.length() == 0) {
return text;
}
try {
byte[] bytes = text.getBytes(textEncoding);
InputStream decodedStream = MimeUtility.decode(new ByteArrayInputStream(bytes), encoding);
byte[] tmp = new byte[bytes.length];
int n = decodedStream.read(tmp);
byte[] res = new byte[n];
System.arraycopy(tmp, 0, res, 0, n);
return new String(res, resultCharset);
} catch (IOException | MessagingException e) {
return text;
}
}
}
And test:
public class EncodingUtilsTest {
#Test
public void koi8r() {
String input = "=?koi8-r?Q?11=5F=F4=ED=5F21=2E05=2Erar?=";
String decode = EncodingUtils.decodeKoi8r(input);
Assertions.assertEquals("11_ТМ_21.05.rar", decode);
}
#Test
public void koi8rWithoutStartTag() {
String input = "=CF=D4=C4=C5=CC=D8=CE=D9=CD =D4=D2=C1=CE=DB=C5=CD =D2=C5=DA=C0=CD=.eml";
String decode = EncodingUtils.decodeKoi8r(input);
Assertions.assertEquals("отдельным траншем резюм=.eml", decode);
}
}
Good day!

Encrypting exception: Given final block not properly padded

I'm trying to decrypt with my own key the following string:
"zW4%3D1p1%2AjR9E"
private static void init(String password) throws Exception {
PBEKeySpec PBEKeySpecification = new PBEKeySpec(password.toCharArray());
keyDES = SecretKeyFactory.getInstance(encrypted_algorithm).generateSecret(PBEKeySpecification);
myCipher = Cipher.getInstance(encrypted_algorithm);
algorithmSpecification = new PBEParameterSpec(salt, iterationCounter);
}
public static void main(String[] args) throws Exception {
String input = "zW4%3D1p1%2AjR9E";
String infoDesencriptada = null;
try {
init("abc123ab");
myCipher.init(2, keyDES, algorithmSpecification);
BASE64Decoder base64Enc = new BASE64Decoder();
byte[] arrayBase64Enc = base64Enc.decodeBuffer(input);
byte[] decryptedBytes = myCipher.doFinal(arrayBase64Enc);
infoDesencriptada = new String(decryptedBytes, "UTF8");
} catch (Exception var5) {
System.out.println("Some exception:" + var5.getMessage());
var5.printStackTrace();
}
}
I'm getting this error: javax.crypto.BadPaddingException: Given final block not properly padded
Any help?
In the question text the data is "zW4%3D1p1%2AjR9E" but in the code it is "zW4%3D1p1%2AjR9E7", note the extra trailing 7.
The input must be a multiple of the block size, 8-bytes for DES so it seems there is a simple entry error in the code.

How to implement google play security verify purchase server side?

I want to implement in-app purchase verification server-side in PHP language.
I tested this link but returned false for correct data set.
The java function:
public class Security {
private static final String TAG = "IABUtil/Security";
private static final String KEY_FACTORY_ALGORITHM = "RSA";
private static final String SIGNATURE_ALGORITHM = "SHA1withRSA";
public static boolean verifyPurchase(String base64PublicKey, String signedData, String signature) {
if (TextUtils.isEmpty(signedData) || TextUtils.isEmpty(base64PublicKey) ||
TextUtils.isEmpty(signature)) {
Log.e(TAG, "Purchase verification failed: missing data.");
return false;
}
PublicKey key = Security.generatePublicKey(base64PublicKey);
return Security.verify(key, signedData, signature);
}
public static PublicKey generatePublicKey(String encodedPublicKey) {
try {
byte[] decodedKey = Base64.decode(encodedPublicKey);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_FACTORY_ALGORITHM);
return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
} catch (InvalidKeySpecException e) {
Log.e(TAG, "Invalid key specification.");
throw new IllegalArgumentException(e);
} catch (Base64DecoderException e) {
Log.e(TAG, "Base64 decoding failed.");
throw new IllegalArgumentException(e);
}
}
public static boolean verify(PublicKey publicKey, String signedData, String signature) {
...
}
}
I tried this code:
function verify_market_in_app($signed_data, $signature, $public_key_base64)
{
$key = "-----BEGIN PUBLIC KEY-----\n".
chunk_split($public_key_base64, 64,"\n").
'-----END PUBLIC KEY-----';
//using PHP to create an RSA key
$key = openssl_get_publickey($key);
//$signature should be in binary format, but it comes as BASE64.
//So, I'll convert it.
$signature = base64_decode($signature);
//using PHP's native support to verify the signature
$result = openssl_verify(
$signed_data,
$signature,
$key,
OPENSSL_ALGO_SHA1);
if (0 === $result)
{
return false;
}
else if (1 !== $result)
{
return false;
}
else
{
return true;
}
}
but this isn't work correctly.
I use openssl_error_string() function and get this error:
error:0906D064:PEM routines:PEM_read_bio:bad base64 decode
Can any body help?

MD5 format in Java [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Generate MD5 hash in Java
Can some one tell me how to convert a string into MD5 format in Java?
I have code like this, but I want in MD5 format with 32 characters.
UUID uuid = UUID.randomUUID();
String token = uuid.toString().substring(0,12);
Implemenation
import java.security.MessageDigest;
import java.math.BigInteger;
import java.lang.String
public class SecurityUtil {
public static String stringToMD5(String string) throws NoSuchAlgorithmException {
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
messageDigest.update(string.getBytes(Charset.forName("UTF-8")),0,string.length());
return new BigInteger(1,messageDigest.digest()).toString(16);
}
}
Usage:
System.out.println(String.format("MD5: %s", stringToMD5("P#$$\\/\\/R|)")));
Output:
MD5: 91162629d258a876ee994e9233b2ad87*
In this sample was used the coding UTF-8.
What is Charset ?
What is MessageDigest ?
What is UTF-8 >
*md5 is example from Wikipedia.
I got bored again...
/**
* #author BjornS
* #created 2. sep. 2010
*/
public enum HashUtil {
SHA1("SHA1"), MD5("MD5"), MD2("MD2"), SHA256("SHA-256"), SHA384("SHA-384"), SHA512("SHA-512");
private final MessageDigest digester;
HashUtil(String algorithm) {
try {
digester = MessageDigest.getInstance(algorithm);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
public String hash(byte[] in) {
return toHexString(digester.digest(in));
}
public String hash(String in) {
return hash(in.getBytes());
}
public String hash(String in, Charset characterSet) {
return hash(in.getBytes(characterSet));
}
public byte[] hashToByteArray(String in) {
return digester.digest(in.getBytes());
}
public byte[] hashToByteArray(String in, Charset characterSet) {
return digester.digest(in.getBytes(characterSet));
}
public byte[] hashToByteArray(byte[] in) {
return digester.digest(in);
}
private String toHexString(byte[] digest) {
StringBuffer hexStr = new StringBuffer(40);
for (byte b : digest) {
hexStr.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1));
}
return hexStr.toString();
}
}
-
/*** ***/
// Use Charsets from Google Guava rather than manually code the charset request, you also don't have to catch exceptions this way! :)
pulic static void main(String... args) {
UUID uuid = UUID.randomUUID();
String uuidString = uuid.toString().substring(0,12);
String token = HashUtil.MD5.hash(uuidString,Charsets.UTF_8);
}
This worked for me..
UUID uuid = UUID.randomUUID();
String token = MD5.digest(uuid.toString().substring(0,12));
thanks for all the answers guys.

Categories