Retrieving sidHistory from LDAP with Java - java

I can retrieve objectSID and many other attributes without error, but not sidHistory (I need sidHistory to see which account in domain A corresponds to an account in domain B).
Here's the code that works for most attributes, including objectSID:
void dumpCSV(Attributes attrs, String[] displayList, Logger lg) {
// Assume we're only dealing with single valued attributes (for now)
StringBuilder sb = new StringBuilder();
for (String attName : displayList) {
String name = attName.trim().toLowerCase();
Attribute att = attrs.get(name);
if (sb.length() > 0)
sb.append(",");
if (att != null) {
String v = "?";
try {
if ((name.equals("objectsid")) || (name.equals("sidhistory")))
v = binString(att);
else {
v = (String) att.get();
if (name.equals("pwdlastset") || name.equals("lastlogontimestamp") || name.equals("lastlogon") || name.equals("accountexpires"))
v = TickConverter.tickDate(v);
}
sb.append(Logger.tidyString(v));
} catch (NamingException e) {
System.err.println("NamingException, " + e);
return;
}
}
}
lg.logln(sb.toString());
}
}
static String binString(Attribute att) {
try {
byte bin[] = (byte[]) att.get();
return decodeSID(bin);
} catch (NamingException e) {
System.err.println("NamingException, " + e);
return "?";
}
}
// taken from http://www.adamretter.org.uk/blog/entries/LDAPTest.java, in turn borrowed from Oracle docs
public static String decodeSID(byte[] sid) {
final StringBuilder strSid = new StringBuilder("S-");
// get version
final int revision = sid[0];
strSid.append(Integer.toString(revision));
//next byte is the count of sub-authorities
final int countSubAuths = sid[1] & 0xFF;
//get the authority
long authority = 0;
//String rid = "";
for(int i = 2; i <= 7; i++) {
authority |= ((long)sid[i]) << (8 * (5 - (i - 2)));
}
strSid.append("-");
strSid.append(Long.toHexString(authority));
//iterate all the sub-auths
int offset = 8;
int size = 4; //4 bytes for each sub auth
for(int j = 0; j < countSubAuths; j++) {
long subAuthority = 0;
for(int k = 0; k < size; k++) {
subAuthority |= (long)(sid[offset + k] & 0xFF) << (8 * k);
}
strSid.append("-");
strSid.append(subAuthority);
offset += size;
}
return strSid.toString();
}
If I try to retrieve sidHistory using this, tyhe value I get is "?".
Even if I use a namingEnumeration, as I think I probably should, I get "Exception in thread "AWT-EventQueue-0" java.util.NoSuchElementException: Vector Enumeration", probably because I am trying to save it to the wrong typoe (and I've tried a few different types).
snippet is :
String v;
NamingEnumeration nenum = att.getAll();
while (nenum.hasMore()) {
v = "";
if (name.equals("objectsid")) {
v = binString(att);
nenum.next();
} else if (name.equals("sidhistory")) {
nenum.next();
String[] vv = ((String[]) nenum.next());
v = vv[0];
} else
v = (String) nenum.next();
if (name.equals("pwdlastset") || name.equals("lastlogontimestamp") || name.equals("lastlogon") || name.equals("accountexpires"))
v = TickConverter.tickDate(v);
lg.logln(name + "=" + Logger.tidyString(v));
}

We used some code similar to:
We note we saw it at http://tomcatspnegoad.sourceforge.net/xref/net/sf/michaelo/tomcat/realm/ActiveDirectoryRealm.html#L566
...
Attribute sidHistory = roleAttributes.get("sIDHistory;binary");
List<String> sidHistoryStrings = new LinkedList<String>();
if (sidHistory != null)
{
NamingEnumeration<?> sidHistoryEnum = sidHistory.getAll();
while (sidHistoryEnum.hasMore())
{
byte[] sidHistoryBytes = (byte[]) sidHistoryEnum.next();
sidHistoryStrings.add(new Sid(sidHistoryBytes).toString());
}
...
}
sidHistory is multi-valued and binary (octetString) is what cause most people headaches.
Hope this helps.

Related

How toUnit Test ZipOutputStream Or verify the CSVWriter in Java

public void writeEnvToCsv(int customerId, ZipOutputStream zos, List<SummaryDetailsResponse> summaryDetailsResponseList, QueryHelper queryHelper) {
//Headers size = size(No of distinct entities) * 2 + 1
final CsvWriter writer = new CsvWriter(new OutputStreamWriter(zos), new CsvWriterSettings());
final String[] headers = new String[summaryDetailsResponseList.get(0).getEntities().size() * 2 + 1];
String header;
int index = 0, i, k;
headers[index++] = Entities;
for (i = 0; i < summaryDetailsResponseList.get(0).getEntities().size(); i++) {
header = summaryDetailsResponseList.get(0).getEntities().get(i).getEntityType();
if (valueMap.get(header) != null) {
header = valueMap.get(header);
}
headers[index++] = header + " " + Count;
headers[index++] = header + "(s)";
}
writer.writeHeaders(headers);
for (index = 0; index < summaryDetailsResponseList.size(); index++) {
final String[] values = new String[summaryDetailsResponseList.get(index).getEntities().size() * 2 + 1];
i = 0;
k = 0;
values[i++] = summaryDetailsResponseList.get(index).getRecordName();
for (; i <= summaryDetailsResponseList.get(index).getEntities().size() * 2; ) {
values[i++] = String.valueOf(summaryDetailsResponseList.get(index).getEntities().get(k).getEntityData().get(0).getTotal());
try {
StringBuilder strConcat = new StringBuilder();
List<String> hostNames = queryHelper.getHostNames(customerId,
String.valueOf(summaryDetailsResponseList.get(index).getEntities().get(k).getEntityData().get(0).getQuery()));
for (String host : hostNames) {
if (strConcat.toString().equals(""))
strConcat.append(host);
else
strConcat.append(", ").append(host);
}
values[i++] = strConcat.toString();
} catch (Exception e) {
e.printStackTrace();
}
k++;
}
writer.writeRow(CSVUtils.escapeCSVRow(values));
}
writer.flush();
}
Basically I want to write UT to verify this function. Can we verify the CSVWriter that it has written correct data for headers and rows or ZipOutputStream in any way.
I was able to verify the records writer has written if I pass writer to the function instead of creating it inside the function but I don't want to do this.

How to divide a sentence to words and compare with another string?

I have saved the units in .txt file. These I am getting in an array list. Now I want to check if any of the units present in the string.
List contains :
"units", "kg", "kilogms", "kilo", "literes",
"Liter", "packets", "packet", "gms", "grams", "half kg"
Like, if I have a string - 1kg rice, I want to get numbers from this string and I want to divide this sentence to words and want to compare with each item from array list of units. If it is present I want to save it. So I want to store 1kg and rice separately. string may contain any spaces I want to trim all those spaces and check compare.
Getting text file in an array list.
public class ReadTextFiles {
public static List<String> readItemNamesFile(Context context) {
String sText = null;
List<String> stringList;
try{
InputStream is = context.getResources().openRawResource(R.raw.item_names);
//Use one of the above as per your file existing folder
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
sText = new String(buffer, "UTF-8");
String[] sTextArray = sText.replace("\"", "").split(",");
stringList = new ArrayList<String>(Arrays.asList(sTextArray));
System.out.print(stringList);
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return stringList;
}
}
public void getUnits()
{
List<String> units = new ArrayList<>();
units = ReadTextFiles.readUnitsFile(getActivity());
System.out.print(units.size());
}
Now I want to compare string suppose its "1 kg potato".Then should find potato from the array list. Also it should be case insensitive.
This is the full solution of your requirement as I understood:
String measuring = "\"units\", \"kg\", \"kilogms\", \"kilo\", \"literes\", \"Liter\", \"packets\", \"packet\", \"gms\", \"grams\", \"half kg\"";
String items = "\"Potato\", \"rice\", \"Eggs\", \"Maggi\", \"Dryfruits\", \"Maza\", \"cold drink\", \"sauce\", \"catchup\", \"coconut oil\"";
String matching = "Kg500 Potato";//"Potato 1 kg";
String item = "", measuringUnit = "", quantity = "";
private void findOut() {
String[] sMeasuringArray = measuring.replace("\"", "").split(", ");
ArrayList<String> measuringList = new ArrayList<String>(Arrays.asList(sMeasuringArray));
String[] sItemsArray = items.replace("\"", "").split(", ");
ArrayList<String> itemsList = new ArrayList<String>(Arrays.asList(sItemsArray));
String[] sMatchingArray = matching.split(" ");
matching = matching.toUpperCase();
for (int i = 0; i < measuringList.size(); i++) {
if (matching.contains(measuringList.get(i).toUpperCase())) {
measuringUnit = measuringList.get(i).trim();
break;
}
}
for (int i = 0; i < itemsList.size(); i++) {
if (matching.contains(itemsList.get(i).toUpperCase())) {
item = itemsList.get(i).trim();
break;
}
}
if (matching!= null) {
String[] part = matching.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
for (int k = 0; k < part.length; k++) {
try {
Integer.parseInt(part[k]);
quantity = part[k];
break;
} catch (Exception ex) {
continue;
}
}
}
/*if (sMatchingArray != null) {
if (sMatchingArray.length == 3) {
for (int j = 0; j < sMatchingArray.length; j++) {
if (measuringUnit.trim().equals(sMatchingArray[j].trim())) {
quantity = sMatchingArray[j - 1].trim();
break;
}
}
} else if (sMatchingArray.length == 2) {
String[] part = matching.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
for (int k = 0; k < part.length; k++) {
try {
Integer.parseInt(part[k]);
quantity = part[k];
break;
} catch (Exception ex) {
continue;
}
}
}
}*/
Log.e("Solution: ", "item = " + item + ", measuringUnit = " + measuringUnit + ", quantity = " + quantity);
}
I'm gonna be using algorithmic approach for the answer. So here it goes:
strItem = "1kg rice";
//Run a loop through the list of units and for each unit check this
if (strItem.contains(list.get(index)))
//Do the needful and break

Java with Pagination

I am working on writing a java client code which calls a web service. When I make a call to one of my client's web service, its accepting the input parameter like below:
KalturaFilterPager pager = new KalturaFilterPager();
pager.pageIndex = 1;
pager.pageSize = 50;
So If i have 430 records, I need to change the input parameter everytime like pageIndex =2 pageSize =50 like this to get all the records.
Now my requirement is I want to retrieve all my records in one page. How can I do this without specifying pageSize =431 as this record number might change in the future.
My code is:
private static String getMediaMetadata() throws KalturaApiException,
IOException, ParserConfigurationException, SAXException {
getKalturaClient();
String country = null;
KalturaMediaService mediaService = client.getMediaService();
System.out.println("Got the mediaservice" + mediaService);
KalturaMediaEntryFilter filter = new KalturaMediaEntryFilter();
KalturaFilterPager pager = new KalturaFilterPager();
pager.pageIndex = 1;
pager.pageSize = 50;
KalturaMediaListResponse mediaResponse = mediaService.list(filter,
pager);
if (mediaResponse.totalCount > 0) {
System.out.println("mediaResponse.totalCount"
+ mediaResponse.totalCount);
// pager.pageSize = mediaResponse.objects;
List<KalturaMediaEntry> mediaEntriesList = mediaResponse.objects;
if (mediaEntriesList != null && mediaEntriesList.size() > 0) {
for (int i = 0; i < mediaEntriesList.size(); i++) {
System.out.println("mediaEntriesList.size()-------->"
+ mediaEntriesList.size());
KalturaMediaEntry media = mediaEntriesList.get(i);
if (media != null) {
System.out.println("Media ID -------->" + media.id);
KalturaMetadataListResponse metadataResp = getMetadata(media.id);
if (metadataResp != null && metadataResp.totalCount > 0) {
System.out.println("Got the metadataResp"
+ metadataResp.totalCount);
List<KalturaMetadata> metadataObjs = metadataResp.objects;
if (metadataObjs != null && metadataObjs.size() > 0) {
System.out.println("got the metadaobjs");
for (int j = 0; j < metadataObjs.size(); j++) {
KalturaMetadata metadata = metadataObjs
.get(j);
if (metadata != null) {
System.out
.println("metadata not null --------->"
+ metadata);
String xml = metadata.xml;
if (xml != null) {
System.out
.println("xml not null --------->"
+ xml);
country = parseXml(xml);
if (country != null) {
System.out
.println("Country Value --------->"
+ country);
}
}
}
}
}
}
}
}
}
}
return country;
}
is there any way to get total number of records before actually getting records? Is there such an API ? If so, call that first use that value as the page size instead.

String index out of Bounds Exception error

I am making a program to read .java files and extract all comments from it and write it to an html file. The file works mostly but i am having trouble extracting the names of each method as it confuses "Exception{" as a separate class/method.
So far this is the code i have and i believe it is almost done.
http://pastebin.com/qrbJAaW3
public class ParseDoc {
static String fileName = null;
static String outputR = "";
static String inputR = "";
static String[] lines;
static String [] classnames;
static StringBuilder classn = new StringBuilder();
static String classnam = "";
/**
* This Method asks the user for path to input and output file
* then it reads the file and places it on a string for easier sorting.
* The string is sorted line by line into an array and cleaned.
* #return Array of DOC comments
* #throws Exception
*/
public static String[] scanread() throws Exception{
System.out.println("NOTICE: If a valid file path is not entered, the program will not return a DOCHTML document.");
Scanner inputReader = new Scanner(System.in);
System.out.println("Please enter path to input file (ex: C:/Program Files/Code.java : " );
inputR = inputReader.nextLine();
System.out.println("Please enter path to html output file (ex: C:/Program Files/Output.html : " );
outputR = inputReader.nextLine();
inputReader.close();
FileReader file = new FileReader(inputR);
BufferedReader reader = new BufferedReader(file);
String line = reader.readLine();
//NAME OF THE SOURCE FILE
int index = inputR.lastIndexOf("/");
fileName = inputR.substring(index + 1);
int z = 0;
//This loop turns the input file into an String for easier access
while (line!= null){
line = reader.readLine();
z += 1;
}
reader.close();
file.close();
FileReader file2 = new FileReader(inputR);
BufferedReader reader2 = new BufferedReader(file2);
String line2 = reader2.readLine();
lines = new String[z];
int j = 0;
while(line2 != null)
{
line2 = line2.trim();
lines[j] = line2;
line2 = reader2.readLine();
j += 1;
}
reader2.close();
file2.close();
return lines;
}
/**
* Removes all the comments from the Array containing strings
* #param lines contains strings made of input file
* #return Array with removed strings
*/
public static String[] removeComments(String[] lines){
for (int i=0; i <lines.length;i++){
if (lines[i].startsWith("//"))
{
lines[i]="";
}
}
return lines;
}
/**
* This method scans the entire code for name of the classes and methods
* along with their parameters and stores them in an Array for further use
* #param lines
* #return lines array without changing any content
*/
public static String[] classNames(String[] lines)
{
int total = 0;
String[] matches = new String[] {"public ", "class ","private "};
for(int b = 0; b <lines.length;b++)
{
Matcher num = Pattern.compile("\\S+\\s*\\(([^)]*)\\)").matcher(lines[b]);
for (int n = 0; n < 3 ;n++)
{
if (lines[b].contains(matches[n]))
{
while(num.find())
{
total += 1;
}
}
}
}
classnames = new String[total];
for(int z = 0; z<lines.length;z++)
{
Matcher mzz = Pattern.compile("\\w+\\s*\\{").matcher(lines[z]);
for (int k = 0; k < 3; k++)
{
if (lines[z].contains(matches[k])&& !(lines[z].contains("throws "))) //&& !(lines[z].contains("throws "))
{
while(mzz.find())
{
classn.append( mzz.group()+"break");
}
}
}
}
for(int z = 0; z <lines.length;z++)
{
//This matcher with Regex looks for class/method names along with any parameters inside
Matcher m = Pattern.compile("\\S+\\s*\\(([^)]*)\\)").matcher(lines[z]);
int i = 0;
for (int k = 0; k < 3; k++)
{
if (lines[z].contains(matches[k]) )
{
while(m.find())
{
classn.append( m.group()+"break");
continue;
}
}
}
}
classnam = classn.toString();
classnames = classnam.split("break");
/*for(int step = 0; step<classnames.length;step++)
{
System.out.println(classnames[step]);
}*/
return lines;
}
/**
* This method removes all the code from the Array and leaves on the
* Doc comments intact.
* #param lines
* #return lines array with only comments remaining ( code is removed )
*/
public static String[] removeCode(String[] lines)
{
int rep = 0;
while ( rep <lines.length){
lines[rep] = lines[rep].replaceAll("\\*", "Z");
if(!(lines[rep].startsWith("Z") || (lines[rep].startsWith("/")))){
lines[rep]="";
}
lines[rep] = lines[rep].replaceAll("Z", "\\*");
rep += 1;
}
for(int num = 0; num <lines.length; num++)
{
if(lines[num].isEmpty()){
lines[num] = null;
}
}
return lines;
}
/**
* This method removes the remaining stars, slashes and properly formats each comment
* before printing it.
* #param lines The array contains parsed Java Doc comments
* #return
* #throws Exception
*/
public static String[] writeTo(String[] lines) throws Exception
{
BufferedWriter outputWriter = null;
outputWriter = new BufferedWriter(new FileWriter(outputR));
StringBuilder writeTo = new StringBuilder();
writeTo.append("<html>\n<body>\n<h2><mark> JAVA DOC COMMENTS</mark> </h2>\n<pre>\n"
+"<big><b>Source File:</b> </big>" +"<big>"+ fileName+"</big>" + "\n\n");
for(int step = 0; step<lines.length;step++)
{
if(!(lines[step] == null))
{
lines[step] = lines[step].replace("#author", "<b>Author: </b>\n&nbsp&nbsp&nbsp");
lines[step] = lines[step].replace("#since", "<b>Since: </b>\n&nbsp&nbsp&nbsp");
lines[step] = lines[step].replace("#version", "<b>Version: </b>\n&nbsp&nbsp&nbsp");
lines[step] = lines[step].replace("#param", "<b>Parameter: </b>\n&nbsp&nbsp&nbsp");
lines[step] = lines[step].replace("#return", "<b>Return: </b>\n&nbsp&nbsp&nbsp");
//lines[step] = lines[step].replace("*", "");
}
}
outputWriter.write(writeTo.toString());
//write to HTML
int countz = 0;
int comcount = 0;
//classnames[]
for(int resum = 0; resum<lines.length;resum++)
{
if(lines[resum] != null)
{
if( lines[resum].charAt(0) == '*' )
{
lines[resum] = lines[resum].replace("*","");
}
}
}
for(int i = 0; i < classnames.length; i++)
{
System.out.println(classnames[i]);
}
for(int resum = 0; resum<lines.length;resum++)
{
if(lines[resum] != null)
{
if( lines[resum].charAt(0) == '/' )
{
if(lines[resum].endsWith("*"))
{
lines[resum] = lines[resum].replace("/**","<b>"+classnames[countz]+"</b>");
countz++;
}
}
if( lines[resum].charAt(0) == '/' )
{
lines[resum] = lines[resum].replace("/","\n");
}
}
}
/*for(int resum = 0; resum<lines.length;resum++)
{
}*/
for(int f = 0; f<lines.length;f++)
{
if(lines[f] != null)
{
/*if(lines[f].startsWith("//") && lines[f].length() == 2)
{
lines[f] = "TEEEST";
countz++;
}*/
outputWriter.write(lines[f]+"\n");
}
}
outputWriter.close();
return null;
}
}
Console:
Please enter path to input file (ex: C:/Program Files/Code.java :
I:\ICS4U0\DocParse\src\java_doc_parse\ParseDoc.java
Please enter path to html output file (ex: C:/Program Files/Output.html :
I:\ICS4U0\DocParse\src\java_doc_parse\ParseDochh.html
ParseDoc {
scanread()
removeComments(String[] lines)
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at java_doc_parse.ParseDoc.writeTo(ParseDoc.java:285)
at java_doc_parse.Execute.main(Execute.java:14)
classNames(String[] lines)
removeCode(String[] lines)
writeTo(String[] lines)
I am not sure what is causing this error. Is there a way to fix it or should i just give up on adding class names to comments altogether?
Sorry if i am lacking some information, but i am quite confused myself.
The error seems to be because you call charAt(0) on what appears to be an empty string.
You already have a null check above, I don't know if it's valid (can your lines ever be null?), but I would change that to a length check, possibly combined with the existing null check.
if (lines[resum] != null && lines[resum].length > 0) {
I think this is where your error resides:
for(int resum = 0; resum<lines.length;resum++)
{
if(lines[resum] != null)
{
if( lines[resum].charAt(0) == '/' )
{
if(lines[resum].endsWith("*"))
{
lines[resum] = lines[resum].replace("/**","<b>"+classnames[countz]+"</b>");
countz++;
}
}
if( lines[resum].charAt(0) == '/' )
{
lines[resum] = lines[resum].replace("/","\n");
}
}
}
Try this instead, move the null check before entering the for loop:
if(lines[0] != null)
{
for(int resum = 0; resum<lines.length;resum++)
{
if( lines[resum].charAt(0) == '/' )
{
if(lines[resum].endsWith("*"))
{
lines[resum] = lines[resum].replace("/**","<b>"+classnames[countz]+"</b>");
countz++;
}
}
if( lines[resum].charAt(0) == '/' )
{
lines[resum] = lines[resum].replace("/","\n");
}
}
}

Encryption/Decryption in java

Hi i found some code after do some Google and i am using this code to Encrypt the string (witch i set as parameter in web-service)
and it's working fine, it's to hard for me to understand this code so put hole class.
public class RSA {
Vector<Object> vectEnc;
Object enc[];
private long P, Q;
private long N, M, E = 11;
private long D;
public RSA() {
P = 6151;
Q = 8807;
N = P * Q;
M = (P - 1) * (Q - 1);
E = 11;
D = 44310191;
vectEnc = new Vector<Object>();
}
public String doEncryption(String message) {
try {
String str = new BASE64Encoder().encode(message.getBytes("UTF-8"));
String encString = "";
for (int i = 0; i < str.length(); i += 3) {
String tempAsci = "1";
String tempStr;
for (int h = 0; h < 3; h++) {
int total = i + h;
if (total < str.length()) {
tempStr = String.valueOf((int) (str.subSequence(total,
total + 1).charAt(0)) - 30);
if (tempStr.length() < 2) {
tempStr = "0" + tempStr;
}
} else {
break;
}
tempAsci = tempAsci + tempStr;
}
vectEnc.add(tempAsci + "1");
}
enc = vectEnc.toArray();
vectEnc.removeAllElements();
for (int i = 0; i < enc.length; i++) {
long base = Long.parseLong(enc[i].toString());
long powMod = powMod(base, E, N);
encString = encString + String.valueOf(powMod) + " ";
}
return encString;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public String doDecryption(String codeMsg) {
String[] decryptArray = codeMsg.split(" ");
String decryptStr = "";
String originalStr = "";
for (int i = 0; i < decryptArray.length; i++) {
long base = Long.parseLong(decryptArray[i]);
long powMod = powMod(base, D, N);
String powModString = String.valueOf(powMod);
decryptStr = decryptStr
+ powModString.subSequence(1, powModString.length() - 1);
}
for (int i = 0; i < decryptStr.length(); i += 2) {
char ch = (char) (Integer.parseInt(decryptStr.subSequence(i, i + 2)
.toString()) + 30);
originalStr = originalStr + ch;
}
BASE64Decoder decoder = new BASE64Decoder();
byte[] decBytes = null;
try {
decBytes = decoder.decodeBuffer(originalStr);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String decodeStr = new String(decBytes);
return decodeStr;
}
public long powMod(long base, long exp, long modula) {
long accum = 1;
int i = 0;
long base2 = base;
while ((exp >> i) > 0) {
if (((exp >> i) & 1) == 1) {
accum = mo((accum * base2), modula);
}
base2 = mo((base2 * base2), modula);
i++;
}
return accum;
}
public long mo(long g, long l) {
return (long) (g - (l * Math.floor(g / l)));
}
}
But the problem is when the String Length is more the 56 it throw the Exception Like
java.lang.NumberFormatException: For input string: "174-17-201"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Long.parseLong(Unknown Source)
at java.lang.Long.parseLong(Unknown Source)
at com.info.test.RSA.doEncryption(RSA.java:49)
at com.info.test.Test.main(Test.java:56)
i even no what is the algorithm is use by this code ,i do some Google and i found simple solution is make a part of string and do Encryption it Like this.
int MAX_LAN = 55;
List<String> splitEqually = splitEqually(string,MAX_LAN);
String encodeString = "";
for (int i = 0; i < splitEqually.size(); i++) {
encodeString +=rsa.doEncryption(splitEqually.get(i));
}
System.out.println(encodeString);
public static List<String> splitEqually(String text, int size) {
List<String> ret = new ArrayList<String>((text.length() + size - 1) / size);
for (int start = 0; start < text.length(); start += size) {
ret.add(text.substring(start, Math.min(text.length(), start + size)));
}
return ret;
}
and it working fine , so is it proper method or not ??
I would strongly suggest using Java's built-in cryptographic libraries for this. Follow this series of articles on how to perform RSA encryption/decryption in Java:
http://www.javamex.com/tutorials/cryptography/rsa_encryption.shtml

Categories

Resources