What encoding is used in "Q29sbGVjdGlvblR5cGU6NTUwMTY2Mw=="? [duplicate] - string

How do I return a base64 encoded string given a string?
How do I decode a base64 encoded string into a string?

Encode
public static string Base64Encode(string plainText)
{
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
return System.Convert.ToBase64String(plainTextBytes);
}
Decode
public static string Base64Decode(string base64EncodedData)
{
var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}

One liner code:
Note: Use System and System.Text directives.
Encode:
string encodedStr = Convert.ToBase64String(Encoding.UTF8.GetBytes("inputStr"));
Decode:
string inputStr = Encoding.UTF8.GetString(Convert.FromBase64String(encodedStr));

I'm sharing my implementation with some neat features:
uses Extension Methods for Encoding class. Rationale is that someone may need to support different types of encodings (not only UTF8).
Another improvement is failing gracefully with null result for null entry - it's very useful in real life scenarios and supports equivalence for X=decode(encode(X)).
Remark: Remember that to use Extension Method you have to (!) import the namespace with using keyword (in this case using MyApplication.Helpers.Encoding).
Code:
namespace MyApplication.Helpers.Encoding
{
public static class EncodingForBase64
{
public static string EncodeBase64(this System.Text.Encoding encoding, string text)
{
if (text == null)
{
return null;
}
byte[] textAsBytes = encoding.GetBytes(text);
return System.Convert.ToBase64String(textAsBytes);
}
public static string DecodeBase64(this System.Text.Encoding encoding, string encodedText)
{
if (encodedText == null)
{
return null;
}
byte[] textAsBytes = System.Convert.FromBase64String(encodedText);
return encoding.GetString(textAsBytes);
}
}
}
Usage example:
using MyApplication.Helpers.Encoding; // !!!
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Test1();
Test2();
}
static void Test1()
{
string textEncoded = System.Text.Encoding.UTF8.EncodeBase64("test1...");
System.Diagnostics.Debug.Assert(textEncoded == "dGVzdDEuLi4=");
string textDecoded = System.Text.Encoding.UTF8.DecodeBase64(textEncoded);
System.Diagnostics.Debug.Assert(textDecoded == "test1...");
}
static void Test2()
{
string textEncoded = System.Text.Encoding.UTF8.EncodeBase64(null);
System.Diagnostics.Debug.Assert(textEncoded == null);
string textDecoded = System.Text.Encoding.UTF8.DecodeBase64(textEncoded);
System.Diagnostics.Debug.Assert(textDecoded == null);
}
}
}

Based on the answers by Andrew Fox and Cebe, I turned it around and made them string extensions instead of Base64String extensions.
public static class StringExtensions
{
public static string ToBase64(this string text)
{
return ToBase64(text, Encoding.UTF8);
}
public static string ToBase64(this string text, Encoding encoding)
{
if (string.IsNullOrEmpty(text))
{
return text;
}
byte[] textAsBytes = encoding.GetBytes(text);
return Convert.ToBase64String(textAsBytes);
}
public static bool TryParseBase64(this string text, out string decodedText)
{
return TryParseBase64(text, Encoding.UTF8, out decodedText);
}
public static bool TryParseBase64(this string text, Encoding encoding, out string decodedText)
{
if (string.IsNullOrEmpty(text))
{
decodedText = text;
return false;
}
try
{
byte[] textAsBytes = Convert.FromBase64String(text);
decodedText = encoding.GetString(textAsBytes);
return true;
}
catch (Exception)
{
decodedText = null;
return false;
}
}
}

A slight variation on andrew.fox answer, as the string to decode might not be a correct base64 encoded string:
using System;
namespace Service.Support
{
public static class Base64
{
public static string ToBase64(this System.Text.Encoding encoding, string text)
{
if (text == null)
{
return null;
}
byte[] textAsBytes = encoding.GetBytes(text);
return Convert.ToBase64String(textAsBytes);
}
public static bool TryParseBase64(this System.Text.Encoding encoding, string encodedText, out string decodedText)
{
if (encodedText == null)
{
decodedText = null;
return false;
}
try
{
byte[] textAsBytes = Convert.FromBase64String(encodedText);
decodedText = encoding.GetString(textAsBytes);
return true;
}
catch (Exception)
{
decodedText = null;
return false;
}
}
}
}

You can use below routine to convert string to base64 format
public static string ToBase64(string s)
{
byte[] buffer = System.Text.Encoding.Unicode.GetBytes(s);
return System.Convert.ToBase64String(buffer);
}
Also you can use very good online tool OnlineUtility.in to encode string in base64 format

URL safe Base64 Encoding/Decoding
public static class Base64Url
{
public static string Encode(string text)
{
return Convert.ToBase64String(Encoding.UTF8.GetBytes(text)).TrimEnd('=').Replace('+', '-')
.Replace('/', '_');
}
public static string Decode(string text)
{
text = text.Replace('_', '/').Replace('-', '+');
switch (text.Length % 4)
{
case 2:
text += "==";
break;
case 3:
text += "=";
break;
}
return Encoding.UTF8.GetString(Convert.FromBase64String(text));
}
}

// Encoding
string passw = "tes123";
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(passw);
string pass = System.Convert.ToBase64String(plainTextBytes);
// Normal
var encodedTextBytes = Convert.FromBase64String(pass);
string plainText = Encoding.UTF8.GetString(encodedTextBytes);

using System;
using System.Text;
public static class Base64Conversions
{
public static string EncodeBase64(this string text, Encoding encoding = null)
{
if (text == null) return null;
encoding = encoding ?? Encoding.UTF8;
var bytes = encoding.GetBytes(text);
return Convert.ToBase64String(bytes);
}
public static string DecodeBase64(this string encodedText, Encoding encoding = null)
{
if (encodedText == null) return null;
encoding = encoding ?? Encoding.UTF8;
var bytes = Convert.FromBase64String(encodedText);
return encoding.GetString(bytes);
}
}
Usage
var text = "Sample Text";
var base64 = text.EncodeBase64();
base64 = text.EncodeBase64(Encoding.UTF8); //or with Encoding

For those that simply want to encode/decode individual base64 digits:
public static int DecodeBase64Digit(char digit, string digit62 = "+-.~", string digit63 = "/_,")
{
if (digit >= 'A' && digit <= 'Z') return digit - 'A';
if (digit >= 'a' && digit <= 'z') return digit + (26 - 'a');
if (digit >= '0' && digit <= '9') return digit + (52 - '0');
if (digit62.IndexOf(digit) > -1) return 62;
if (digit63.IndexOf(digit) > -1) return 63;
return -1;
}
public static char EncodeBase64Digit(int digit, char digit62 = '+', char digit63 = '/')
{
digit &= 63;
if (digit < 52)
return (char)(digit < 26 ? digit + 'A' : digit + ('a' - 26));
else if (digit < 62)
return (char)(digit + ('0' - 52));
else
return digit == 62 ? digit62 : digit63;
}
There are various versions of Base64 that disagree about what to use for digits 62 and 63, so DecodeBase64Digit can tolerate several of these.

You can display it like this:
var strOriginal = richTextBox1.Text;
byte[] byt = System.Text.Encoding.ASCII.GetBytes(strOriginal);
// convert the byte array to a Base64 string
string strModified = Convert.ToBase64String(byt);
richTextBox1.Text = "" + strModified;
Now, converting it back.
var base64EncodedBytes = System.Convert.FromBase64String(richTextBox1.Text);
richTextBox1.Text = "" + System.Text.Encoding.ASCII.GetString(base64EncodedBytes);
MessageBox.Show("Done Converting! (ASCII from base64)");
I hope this helps!

To encode a string into a base64 string in C#, you can use the Convert.ToBase64String method:
string originalString = "Hello World";
string encodedString = Convert.ToBase64String(Encoding.UTF8.GetBytes(originalString));
To decode a base64 encoded string into a string in C#, you can use the Convert.FromBase64String method:
string encodedString = "SGVsbG8gV29ybGQ=";
string originalString = Encoding.UTF8.GetString(Convert.FromBase64String(encodedString));

Related

XSSFCell in Apache POI encodes certain character sequences as unicode character

XSSFCell seems to encode certain character sequences as unicode characters. How can I prevent this? Do I need to apply some kind of character escaping?
e.g.
cell.setCellValue("LUS_BO_WP_x24B8_AI"); // The cell value now is „LUS_BO_WPⒸAI"
In Unicode Ⓒ is U+24B8
I've already tried setting an ANSI font and setting the cell type to string.
This character conversion is done in XSSFRichTextString.utfDecode()
I have now written a function that basicaly does the same thing in reverse.
private static final Pattern utfPtrn = Pattern.compile("_(x[0-9A-F]{4}_)");
private static final String UNICODE_CHARACTER_LOW_LINE = "_x005F_";
public static String escape(final String value) {
if(value == null) return null;
StringBuffer buf = new StringBuffer();
Matcher m = utfPtrn.matcher(value);
int idx = 0;
while(m.find()) {
int pos = m.start();
if( pos > idx) {
buf.append(value.substring(idx, pos));
}
buf.append(UNICODE_CHARACTER_LOW_LINE + m.group(1));
idx = m.end();
}
buf.append(value.substring(idx));
return buf.toString();
}
Based on what #matthias-gerth suggested with little adaptations:
Create your own XSSFRichTextString class
Adapt XSSFRichTextString.setString like this: st.setT(s); >> st.setT(escape(s));
Adapt the constructor of XSSFRichTextString like this: st.setT(str); >> st.setT(escape(str));
Add this stuff in XSSFRichTextString (which is very near to Matthias suggestion):
private static final Pattern PATTERN = Pattern.compile("_x[a-fA-F0-9]{4}");
private static final String UNICODE_CHARACTER_LOW_LINE = "_x005F";
private String escape(String str) {
if (str!=null) {
Matcher m = PATTERN.matcher(str);
if (m.find()) {
StringBuffer buf = new StringBuffer();
int idx = 0;
do {
int pos = m.start();
if( pos > idx) {
buf.append(str.substring(idx, pos));
}
buf.append(UNICODE_CHARACTER_LOW_LINE + m.group(0));
idx = m.end();
} while (m.find());
buf.append(str.substring(idx));
return buf.toString();
}
}
return str;
}

Limit string to eight characters and return it with asterisk

I have a studentDto. I want to determine the number
of characters for LastName. If number of characters is greater
than 8, I want to return the last name of 8 characters with two asterisk thus
cutting off the other characters
e.g Abumadem**
Here is how I started.I am unable to get it to work. Can you please assist?
public class StudentDto
{
public string Firstname { get; set; }
public string EmailAddress { get; set; }
public string LastName
{
get
{
var checkLength = LastName.Length;
string First8Chars = string.Empty;
int count=0;
List<char> storeStrings = new List<char>();
if (checkLength > 8)
{
foreach (var c in LastName)
{
storeStrings.Add(c);
if ()
{
}
count++;
}
}
}
}
}
Here is new attempt and no luck yet.
public class StudentDto
{
public string Firstname { get; set; }
public string EmailAddress { get; set; }
public string LastName
{
get
{
var checkLength = LastName.Length;
string First8Chars = string.Empty;
if (checkLength > 8)
{
First8Chars = LastName.Substring(0, 7) + "**";
return First8Chars;
}
}
set { }
}
}
Just do it like this:
string _backingFieldLastName;
public string LastName
{
get
{
return _backingFieldLastName == null || backingFieldLastName.Length <=8 ?
_backingFieldLastName :
_backingFieldLastName.Substring(0,8) +"**"; // second parameter of substring is count of chars from the start index (first parameter)
}
set
{
_backingFieldLastName = value;
}
}
If you cant use library functions for some reason:
private string _lastName = "";
public string LastName
{
get
{
var checkLength = _lastName.Length;
string First8Chars = string.Empty;
string storeStrings = "";
if (checkLength > 8)
{
foreach (var c in _lastName)
{
storeStrings += c;
if (storeStrings.Length == 8)
{
storeStrings += "**";
return storeStrings;
}
}
}
return storeStrings;
}
set { _lastName = value; }
}
One thing I noticed is your use of LastName in the LastName property getter, a big no no, its causing recursion and you probably are getting a stack overflow exception
This could be written more concise, but I'll leave that as an exercise for you
The Linq way:
var lastname = "Abumademal";
var formatted = (new string(lastname.Take(8).ToArray())).PadRight(lastname.Length, '*');
// will yield "Abumadem**"
"Take 8 chars and create a new string from this array, then pad it with as many * as needed."
full implementation:
private string lastname;
public string LastName
{
get
{
if (null == this.lastname)
{
return null;
}
char[] firsteight = this.lastname.Take(8).ToArray();
string tmp = new string(firsteight);
// padding this way wasn't the actual requirement ...
string result = tmp.PadRight(this.lastname.Length, '*');
return result;
}
set
{
this.lastname = value;
}
}

Reverse String Palindrome

Hi I am trying to reverse a String to make a palindrome. Can someone please give me a tutorial on how to reverse a string? I have read some tutorials online and I have tried applying them to the palindrome program that i am writing but have not been successful.
import java.util.Random;
public class IterativePalindromGenerator {
public static void main(String[] args) {
Random random = new Random();
int floorValue = 1;
int cielingValue = 20;
int randomNumber = random.nextInt(cielingValue - floorValue)
+ floorValue;
String alphabetLetters = "abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < randomNumber; i++) {
char generatedLetters = alphabetLetters.charAt(random
.nextInt(alphabetLetters.length()));
String generatedLetterSTRINGType = Character
.toString(generatedLetters);// converts char to string
System.out.print(generatedLetterSTRINGType);
}
}
}
To reverse a string you can use StringBuffers reverse() method:
public String reverse(String stringToReverse) {
return new StringBuffer(stringToReverse).reverse().toString();
}
Hey here is my code from a college course. Our task was to implement a recursive procedure. Hope this can help the community.
package DiskreteMathe;
import java.util.*;
public class AufgabePalindromTestRekursiv {
public static void main (String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Please enter text here:");
String text= sc.next();
System.out.println(testPalindrom(text));
}
public static boolean testPalindrom (String text){
if (text.length()==2 && text.charAt(0)==text.charAt(1) || text.length()==1)
return true;
if(text.charAt(0)!=text.charAt(text.length()-1)){
return false;
} else {
text = text.substring(1, text.length()-1);
return testPalindrom(text);
}
}
}
When creating a palindrome for existing string, you need to think of the cases of even and odd outcome strings. For example, if you input String "abc", you should expect there are two outcome palindrome strings: abccba (even) and abcba (odd).
Here is my code:
public class PalindromeGenerator {
public static void main(String[] args) {
String str = "abc";
String reverse_str = "";
for (int n = str.length(); n>0; n--){
reverse_str += str.substring(n-1, n);
}
String even_str = str + reverse_str;
String odd_str = str.substring(0, str.length()-1) + reverse_str;
System.out.println(even_str); // print "abccba"
System.out.println(odd_str); //print "abcba"
}
}
I Hope this can help you.

update record in recordstore j2me

i want to know the method used to update record in recordstore in j2me. thanks....
Simply use RecordStore.setRecord()
try this
Preferences preferences = new Preferences("ChatAppPref");
preferences.put("login", "y");
preferences.save();
String pIsLogin = preferences.get("login");
Preferences class here
package com.util;
import java.util.*;
import javax.microedition.rms.*;
public class Preferences {
private String mRecordStoreName;
private Hashtable mHashtable;
public Preferences(String recordStoreName)
throws RecordStoreException {
mRecordStoreName = recordStoreName;
mHashtable = new Hashtable();
load();
}
public String get(String key) {
return (String)mHashtable.get(key);
}
public void put(String key, String value) {
if (value == null) value = "";
mHashtable.put(key, value);
}
private void load() throws RecordStoreException {
RecordStore rs = null;
RecordEnumeration re = null;
try {
rs = RecordStore.openRecordStore(mRecordStoreName, true);
re = rs.enumerateRecords(null, null, false);
while (re.hasNextElement()) {
byte[] raw = re.nextRecord();
String pref = new String(raw);
// Parse out the name.
int index = pref.indexOf('|');
String name = pref.substring(0, index);
String value = pref.substring(index + 1);
put(name, value);
}
}
finally {
if (re != null) re.destroy();
if (rs != null) rs.closeRecordStore();
}
}
public void save() throws RecordStoreException {
RecordStore rs = null;
RecordEnumeration re = null;
try {
rs = RecordStore.openRecordStore(mRecordStoreName, true);
re = rs.enumerateRecords(null, null, false);
// First remove all records, a little clumsy.
while (re.hasNextElement()) {
int id = re.nextRecordId();
rs.deleteRecord(id);
}
// Now save the preferences records.
Enumeration keys = mHashtable.keys();
while (keys.hasMoreElements()) {
String key = (String)keys.nextElement();
String value = get(key);
String pref = key + "|" + value;
byte[] raw = pref.getBytes();
rs.addRecord(raw, 0, raw.length);
}
}
finally {
if (re != null) re.destroy();
if (rs != null) rs.closeRecordStore();
}
}
}

String replace in Java ME double space

How can I replace "a b" by "a b" in Java ME?
The replace() method doesn't accept Strings, but only characters. And since a double space contains two characters, I think I have a small problem.
What do you think of this one? I tried one myself.
private String replace(String needle, String replacement, String haystack) {
String result = "";
int index = haystack.indexOf(needle);
if(index==0) {
result = replacement+haystack.substring(needle.length());
return replace(needle, replacement, result);
}else if(index>0) {
result = haystack.substring(0,index)+ replacement +haystack.substring(index+needle.length());
return replace(needle, replacement, result);
}else {
return haystack;
}
}
Here's one function you might use:
public static String replace(String _text, String _searchStr, String _replacementStr) {
// String buffer to store str
StringBuffer sb = new StringBuffer();
// Search for search
int searchStringPos = _text.indexOf(_searchStr);
int startPos = 0;
int searchStringLength = _searchStr.length();
// Iterate to add string
while (searchStringPos != -1) {
sb.append(_text.substring(startPos, searchStringPos)).append(_replacementStr);
startPos = searchStringPos + searchStringLength;
searchStringPos = _text.indexOf(_searchStr, startPos);
}
// Create string
sb.append(_text.substring(startPos,_text.length()));
return sb.toString();
}

Resources