How to obtain the Base64 representation of a string in Android Oreo - java

I need to convert string into base64 under Oreo api level.
I have the following code:
public String genAuthKey(String u, String p){
user = u;
pass = p;
key = user+":"+pass;
byte[] encodedBytes = new byte[0];
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
encodedBytes = Base64.getEncoder().encode(key.getBytes());
Log.e("VERSION IS","O");
}else{
encodedBytes = Base64.getEncoder().encodeToString(key.getBytes()).getBytes();
Log.e("VERSION LESS","O");
}
Log.e("key",new String(encodedBytes,Charset.forName("UTF-8")));
return new String(encodedBytes, Charset.forName("UTF-8"));
}
In else condition, I need code to convert and send the data properly. How can I do that?

first add this import
import android.util.Base64;
then replace your method with a version agnostic variant
public String genAuthKey(String u, String p) {
user = u;
pass = p;
key = user + ":" + pass;
byte[] encodedBytes = Base64.encode(key.getBytes(), Base64.DEFAULT);
Log.e("key", new String(encodedBytes, StandardCharsets.UTF_8));
return new String(encodedBytes, StandardCharsets.UTF_8);
}
Enjoy!

Try this code for encoding kotlin:
var encodedString = Base64.encode("Your String", Base64.DEFAULT).toString(Charsets.UTF_8)
and for decoding:
var decodedString = Base64.decode(encodedString, Base64.DEFAULT).toString(Charsets.UTF_8)

Related

OAuth 401 Unauthorised

so learning still but i'm getting an Error 401 unauthorised back from the code below. I know that the OAuth header works as it works in postman so i'm assuming there is a problem with the POST request / Auth header? Any ideas?
//set timestamp
Long timestamp = System.currentTimeMillis()/1000;
//set nonce ***** call from main system*************************************************************
String aString = randomAlphaNumeric(11);
// other stuff
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
HttpHeaders headers = new HttpHeaders();
String url = "aURL";
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
// String auth = Base64.getEncoder().encodeToString(credentials.getBytes());
List<NameValuePair> oauthHeaders = new ArrayList<>(9);
oauthHeaders.add(new BasicNameValuePair("oauth_consumer_key", "aKey"));
oauthHeaders.add(new BasicNameValuePair("oauth_nonce", aString));
oauthHeaders.add(new BasicNameValuePair("oauth_timestamp", String.valueOf(timestamp)));
oauthHeaders.add(new BasicNameValuePair("oauth_signature_method", "HMAC-SHA1"));
oauthHeaders.add(new BasicNameValuePair("oauth_version", "1.0"));
//generate signature
//encode
String encodedURL = encode(oauthHeaders.toString());
System.out.println("encoded URL:" +encodedURL);
//form base string
String baseString = "POST&"+encode(url).toString()+encodedURL;
System.out.println("Base String: "+baseString);
//form signature
byte[] byteHMAC = null;
try {
Mac mac = Mac.getInstance("HmacSHA1");
SecretKeySpec spec;
if (null == secretKey) {
String signingKey = encode(secretKey) + '&';
spec = new SecretKeySpec(signingKey.getBytes(), "HmacSHA1");
} else {
String signingKey = encode(secretKey) + '&' + encode(secretKey);
spec = new SecretKeySpec(signingKey.getBytes(), "HmacSHA1");
}
mac.init(spec);
byteHMAC = mac.doFinal(baseString.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
String signature = new BASE64Encoder().encode(byteHMAC);
System.out.println("oauth signature: "+signature);
//set signature to params
oauthHeaders.add(new BasicNameValuePair("oauth_signature", signature));
String test = "OAuth "+oauthHeaders.toString();
headers.set("Authorization", test);
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("Name",name.toString());
map.add("Region",region.toString());
HttpEntity<MultiValueMap<String, String>> requestEntity= new HttpEntity<MultiValueMap<String, String>>(headers, map);
System.out.println(requestEntity);
ResponseEntity<String> response= restTemplate.exchange(url ,HttpMethod.POST, requestEntity, String.class);
System.out.println(response.toString());
HttpStatus status = response.getStatusCode();
status.toString();
if(status.equals("200")){
Notification.show("Employer" + name +" added successfully");
}
else{
Notification.show("Unsuccessful, error: "+status);
}
}
removed the URL and consumer key / signature for obvious reasons.
The following System out prints might help as well:
encoded params:
%5Boauth_consumer_key%3aKey%2C%20oauth_nonce%3DWZU8H1B5JA6%2C%20oauth_timestamp%3D1511621759%2C%20oauth_signature_method%3DHMAC-SHA1%2C%20oauth_version%3D1.0%5D
Base String: POST&https%3A%2F%2Fapi.test.payrun.io%2FEmployer%5Boauth_consumer_key%3aKey%2C%20oauth_nonce%3DWZU8H1B5JA6%2C%20oauth_timestamp%3D1511621759%2C%20oauth_signature_method%3DHMAC-SHA1%2C%20oauth_version%3D1.0%5D
oauth signature: DlRJGSzgRIItzz+LzMbgnIfbOqU=
The value of oauth_signature is wrong. You are using asignature as the value of oauth_signature, but you have to compute the correct value for your request and set it to oauth_signature. If the value of oauth_signature is wrong, the server will reject your request. See "3.4. Signature" in RFC 5849 (The OAuth 1.0 Protocol) for details.
For anyone who wants to make this work then please see below for a complete OAuth Generator example :):
public class oAuthGenerator {
private String httpMethod;
private String params;
private String url;
//Required for percent encoding
private static final String ENC = "ASCII";
//Required for nonce
private static final String ALPHA_NUMERIC_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
//As provided by Payrun.io
private static final String secretKey = "aSecretKey";
//As provided by Payrun.io
private static final String consumerKey ="aConsumerKey";
private List veriList;
//Constructor for setting signature base string values.
//#Param url needs to be percent encoded
//#Param params needs to be percent encoded, this is done #Method generateOAuth()
public oAuthGenerator(String httpMethod,String url )throws Exception {
veriList= new ArrayList<String>();
veriList.add("POST");
veriList.add("GET");
veriList.add("PUT");
veriList.add("DELETE");
if (veriList.contains(httpMethod)){
this.httpMethod = httpMethod+"&";}
this.url = URLEncoder.encode(url,ENC)+"&";
}
//A method used to generate the OAuth Authorization header
//#Method randomAlphaNumeric() calls internal method using instance variable ALPHA_NUMERIC_STRING
//#Method getSignature() returns String HMACSHA1 > Base64 encoded value of httpMethod,url,params
public String generateOAuth()throws Exception{
//Set timestamp as seconds from 01-01-1970
Timestamp timestamp = new Timestamp(System.currentTimeMillis()/1000);
Long aTimestamp = timestamp.getTime();
//Set nonce which is a 10 digit random, non repeating alpha-numeric value
String aNonce = randomAlphaNumeric(10);
//Normalize and form param string
String normalizedParams = "oauth_consumer_key="+consumerKey+"&"+"oauth_nonce="+aNonce+"&"+"oauth_signature_method="+"HMAC-SHA1"+"&"+"oauth_timestamp="+ aTimestamp.toString()+"&"+"oauth_version="+"1.0";
//Percent encoded params
params = URLEncoder.encode(normalizedParams,ENC);
//Set signature variable
String signature = getSignature();
//place into required format
String oAuthResult = "OAuth "+"oauth_version="+"\"1.0\""+","+"oauth_consumer_key="+"\"" + consumerKey + "\""+","+"oauth_signature_method="+"\"HMAC-SHA1\""+","+"oauth_timestamp="+"\""+aTimestamp+"\""+","+"oauth_nonce="+"\""+aNonce+"\""+","+"oauth_signature="+"\""+signature+"\"";
return oAuthResult;
}
// A method designed to return a hashed and base64 encoded value.
//#Param aString holds HMAC-SHA1 and Base 64 encoded value of variables httpMethod,url,params
//#Param result holds percent encoded value of aString
private String getSignature()
throws Exception {
//form base string
StringBuilder base = new StringBuilder();
base.append(httpMethod);
base.append(url);
base.append(params);
//Set SecretKey of variable secretKey using HMAC-SHA1 algorithm
SecretKey signingKey = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1");
// Get an hmac_sha1 Mac instance and initialize with the signing key
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(signingKey);
// Compute the hmac on input data bytes, then encode to Base64
String aString = Base64.getEncoder().encodeToString(mac.doFinal(base.toString().getBytes(ENC))).trim();
//Percent encoded the Base64 value
String result = URLEncoder.encode(aString, ENC);
return new String(result);
}
//Required for nonce, returns a random alpha numeric value by using variable ALPHA_NUMERIC_STRING
private static String randomAlphaNumeric(int count) {
StringBuilder builder = new StringBuilder();
while (count-- != 0) {
int character = (int)(Math.random()*ALPHA_NUMERIC_STRING.length());
builder.append(ALPHA_NUMERIC_STRING.charAt(character));
}
return builder.toString();
}
}

One of three functions not being called using QAndroidJniObject

Here is the code that calls three functions from my custom java class:
QAndroidJniObject datafile = QAndroidJniObject::fromString(path);
QAndroidJniObject password = QAndroidJniObject::fromString("asimpletest");
QAndroidJniObject::callStaticObjectMethod("org/qcolocrypt/AESCrypt",
"AESCryptInit",
"(Ljava/lang/String;Ljava/lang/String;)V;",
password.object<jstring>(),
datafile.object<jstring>());
QAndroidJniObject decrypted_data = QAndroidJniObject::callStaticObjectMethod("org/qcolocrypt/AESCrypt",
"decrypt",
"()Ljava/lang/String;");
QAndroidJniObject fname = QAndroidJniObject::callStaticObjectMethod("org/qcolocrypt/AESCrypt",
"getFilename",
"()Ljava/lang/String;");
QAndroidJniObject status = QAndroidJniObject::callStaticObjectMethod("org/qcolocrypt/AESCrypt",
"getStatus",
"()Ljava/lang/String;");
Here is the java code for three of these functions:
The non working one:
public static void AESCryptInit (String passwd, String datafile){
// Initializing variables.
rawdata = null;
status = "";
fileName = datafile;
Log.i("[QCOLOCRYPT]","The filename is " + datafile);
// Transforming the passwd to 16 bytes.
try {
MessageDigest digester = MessageDigest.getInstance("MD5");
InputStream in = new ByteArrayInputStream(Charset.forName(encoding).encode(passwd).array());
byte[] buffer = new byte[NCHARS];
int byteCount;
while ((byteCount = in.read(buffer)) > 0) {
digester.update(buffer, 0, byteCount);
}
keyBytes = digester.digest();
}
catch(Exception e){
status = "Error in key generation: " + e.toString();
}
// Initilizing the crypto engine
try {
cipher = Cipher.getInstance(algorithm);
}
catch(Exception e){
status = "Error in intialization: " + e.toString();
}
secretKeySpec = new SecretKeySpec(keyBytes, "AES");
ivParameterSpec = new IvParameterSpec(keyBytes);
}
And two that work
// Getting status
public static String getStatus(){return status;}
public static String getFilename() {
Log.i("[QCOLOCRYPT]","Getting the file name");
return "The Filename is: " + fileName;
}
The non-working function is not being called because its debug message is NOT being printed, while I get the log message AND the return values of the other two. Logcat does not seem to show any errors, so I'm at a loss. Am I calling it wrong?
Ok, so this isn't exactly an answer. It's more of a workaround, I got the function to work, but the only way I could do it is by returning a String. I've tried with an Integer using (Arguments)I; as the signature but I had the same problem. I modified the Java function to return a status string, changed the signature to reflect that, and everything worked perfectly. Though its weird.

Kraken API - Invalid signature

I'm trying to change a working example from C sharp to Java but i'm struggling and don't know where the problem is. I contacted Kraken and they advised me that I have the wrong signature... The response is:
{"error":["EAPI:Invalid signature"]}
Here's the C sharp version:
private JsonObject QueryPrivate(string a_sMethod, string props = null)
{
// generate a 64 bit nonce using a timestamp at tick resolution
Int64 nonce = DateTime.Now.Ticks;
props = "nonce=" + nonce + props;
string path = string.Format("/{0}/private/{1}", _version, a_sMethod);
string address = _url + path;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(address);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
webRequest.Headers.Add("API-Key", _key);
byte[] base64DecodedSecred = Convert.FromBase64String(_secret);
var np = nonce + Convert.ToChar(0) + props;
var pathBytes = Encoding.UTF8.GetBytes(path);
var hash256Bytes = sha256_hash(np);
var z = new byte[pathBytes.Count() + hash256Bytes.Count()];
pathBytes.CopyTo(z, 0);
hash256Bytes.CopyTo(z, pathBytes.Count());
var signature = getHash(base64DecodedSecred, z);
webRequest.Headers.Add("API-Sign", Convert.ToBase64String(signature));
if (props != null)
{
using (var writer = new StreamWriter(webRequest.GetRequestStream()))
{
writer.Write(props);
}
}
//Make the request
try
{
using (WebResponse webResponse = webRequest.GetResponse())
{
using (Stream str = webResponse.GetResponseStream())
{
using (StreamReader sr = new StreamReader(str))
{
return (JsonObject)JsonConvert.Import(sr);
}
}
}
}
}
The full code is here at:
https://bitbucket.org/arrivets/krakenapi/src/cff138b017c38efde2db1a080fb765790a6d04c8/KrakenClient/KrakenClient.cs?at=master&fileviewer=file-view-default
Here is my Java version:
private void fetch() throws UnsupportedEncodingException, IOException, NoSuchAlgorithmException {
String version = "0";
String key = ".....6";
String secret = "....g==";
long nonce = System.currentTimeMillis();
String props = null;
props = "nonce=" + nonce + props; // I've tried this with and without the 'null' on the end
// url
String url = "https://api.kraken.com";
String path = "/" + version + "/private/" + "Balance";
String address = url + path;
// post req
HttpPost httpPost = new HttpPost(address);
// headers
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
httpPost.setHeader("API-Key", key);
// decode buffer
BASE64Decoder decoder = new BASE64Decoder();
byte[] base64DecodedSecred = decoder.decodeBuffer(secret);
// nonce & props
String np = nonce + (char) 0 + props;
// create byte array
byte[] pathBytes = path.getBytes("UTF-8");
byte[] hash256Bytes = sha256(np);
byte[] z = new byte[pathBytes.length + hash256Bytes.length];
System.arraycopy(pathBytes, 0, z, 0, pathBytes.length);
System.arraycopy(hash256Bytes, 0, z, pathBytes.length, hash256Bytes.length);
// encrypt signature
byte[] signature = hmacEncrypt(z, base64DecodedSecred); // my hmacEncrypt is message, secret (opposite to the c sharp)
BASE64Encoder encoder = new BASE64Encoder();
httpPost.setHeader("API-Sign", encoder.encode(signature));
// Post
List<NameValuePair> nvps = new ArrayList<>();
nvps.add(new BasicNameValuePair("nonce", String.valueOf(nonce)));
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
// Client & Response
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
// parse
JsonParser jp = new JsonParser();
JsonElement root = jp.parse(EntityUtils.toString(entity));
System.out.println(root); // {"error":["EAPI:Invalid signature"]}
// close client
httpClient.close();
}
I'm sorry to have posted a large bits of code, any help would be appreciated. Thank you!
there is no cchmac 512 encryption in your code. that is why you get this EAPI:Invalid signature"

Getting input text back out of MessageDigest

There are many people here on SO suggesting different approaches to the problem that I am having, but non of them seem to work for me. I am currently testing a timestamp server and (among other things, I am sending the server a message) and I need to read that the message exists in the answer. So I am creating a request and preparing it:
MessageDigest digest = MessageDigest.getInstance("SHA1");
String s = "Trolololoooo";
DigestInputStream stream = new DigestInputStream(new ByteArrayInputStream(s.getBytes("UTF-8")), digest)
byte[] digest2 = stream.getMessageDigest().digest();
// timestamp stuff is all org.bouncycastle.tsp.*
TimeStampRequestGenerator timeStampRequestGenerator = new TimeStampRequestGenerator();
timeStampRequestGenerator.setReqPolicy(String.valueOf(new ASN1ObjectIdentifier("1.3.6.1.4.1.13762.3")));
TimeStampRequest timeStampRequest = timeStampRequestGenerator.generate(TSPAlgorithms.SHA1, digest2, BigInteger.valueOf(666));
byte request[] = timeStampRequest.getEncoded();
... skipped the sending part, ok got the answer
InputStream in = con.getInputStream();
TimeStampResp resp = TimeStampResp.getInstance(new ASN1InputStream(in).readObject());
TimeStampResponse response = new TimeStampResponse(resp);
response.validate(timeStampRequest);
Now, from the response, I can successfully read the byte stream like:
byte[] messageImprintDigest1 = response.getTimeStampToken().getTimeStampInfo().getMessageImprintDigest();
for( byte b : messageImprintDigest1) System.out.print(b);
Will output: -3857-93-189410775135085-65-17-1079624-112-81-4079
Anyway, I have been blindly trying all the suggestion that I have found, that would translate back to "Trolololoooo", but no success. Some (not limited to) things I have tried:
String s1 = DigestUtils.sha1Hex(messageImprintDigest1);
String s2 = new String(Hex.decodeHex(s1.toCharArray()), "UTF-8");
// how could that help me..? but nothing to lose here.
String s3 = Hex.encodeHexString(messageImprintDigest1);
String convert = convert(s1);
// String convert1 = convert(s2);
// String convert2 = convert(s3);
int len = s1.length();
byte[] cStr = new byte[len/2];
for(int i = 0; i < len; i+=2) {
cStr[i/2] = (byte)Integer.parseInt(s1.substring(i, i+2), 16);
}
CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();
decoder.onMalformedInput(CodingErrorAction.IGNORE);
ByteBuffer wrap = ByteBuffer.wrap(cStr);
CharBuffer decode = decoder.decode(wrap);
CharBuffer cb = decoder.decode( ByteBuffer.wrap( cStr ));
String s4 = cb.toString();
...
public static String convert(String hex){
ByteBuffer buff = ByteBuffer.allocate(hex.length()/2);
for (int i = 0; i < hex.length(); i+=2) {
buff.put((byte)Integer.parseInt(hex.substring(i, i+2), 16));
}
buff.rewind();
Charset cs = Charset.forName("UTF-8");
CharBuffer cb = cs.decode(buff);
return cb.toString();
}
Anyway, it is probably some obvious stuff I am missing, like that the messageImprintDigest1 doesn't look like a hex string at all (pardon me, I studied geology in university).. This stuff is all very new to me, so it is hard to argue with the compiler or some other stuff out there.
You can't get the original text back from a message digest. It's a one-way process.
Have you tried this simple solution?
byte[] b = "Trolololoooo".getBytes();
String s = new String(b);
System.out.println(s);
will output Trolololoooo.

Java: Encode String in quoted-printable

I am looking for a way to quoted-printable encode a string in Java just like php's native quoted_printable_encode() function.
I have tried to use JavaMails's MimeUtility library. But I cannot get the encode(java.io.OutputStream os, java.lang.String encoding) method to work since it is taking an OutputStream as input instead of a String (I used the function getBytes() to convert the String) and outputs something that I cannot get back to a String (I'm a Java noob :)
Can anyone give me tips on how to write a wrapper that converts a String into an OutputStream and outputs the result as a String after encoding it?
To use this MimeUtility method you have to create a ByteArrayOutputStream which will accumulate the bytes written to it, which you can then recover. For example, to encode the string original:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputStream encodedOut = MimeUtility.encode(baos, "quoted-printable");
encodedOut.write(original.getBytes());
String encoded = baos.toString();
The encodeText function from the same class will work on strings, but it produces Q-encoding, which is similar to quoted-printable but not quite the same:
String encoded = MimeUtility.encodeText(original, null, "Q");
Thats what helps me
#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);
}
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;
}
}

Categories

Resources