add "rotation" when we encrypt an uppercase letter by rotating 13 - encoding

package edu.secretcode;
import java.util.Scanner;
/**
* Creates the secret code class.
*
*
*
*/
public class SecretCode {
/**
* Perform the ROT13 operation
*
* #param plainText
* the text to encode
* #return the rot13'd encoding of plainText
*/
public static String rotate13(String plainText) {
StringBuffer cryptText = new StringBuffer("");
for (int i = 0; i < plainText.length() - 1; i++) {
int currentChar = plainText.charAt(i);
String cS = currentChar+"";
currentChar = (char) ((char) (currentChar - (int) 'A' + 13) % 255 + (int)'A');
if ((currentChar >= 'A') && (currentChar <= 'Z')) {
currentChar = (((currentChar - 'A')+13) % 26) + 'A' - 1;
}
else {
cryptText.append(currentChar);
}
}
return cryptText.toString();
}
/**
* Main method of the SecretCode class
*
* #param args
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (1 > 0) {
System.out.println("Enter plain text to encode, or QUIT to end");
Scanner keyboard = new Scanner(System.in);
String plainText = keyboard.nextLine();
if (plainText.equals("QUIT")) {
break;
}
String cryptText = SecretCode.rotate13(plainText);
String encodedText = SecretCode.rotate13(plainText);
System.out.println("Encoded Text: " + encodedText);
}
}
}
I need to make this rotation work by adding-13 to a character if the resulting character is greater-than 'Z' I am suppose to subtract 'Z' then add 'A' then subtract 1 (the number 1, not the letter '1') and do this only for capital letters. I did this in the if statement and when I typed in "HELLO WORLD!" I got 303923011009295302 and I was suppose to get "URYYB JBEYQ!" and the program is not encoding correctly. Any help would be appreciated. Thanks in advance.

You're appending an int rather than a char to cryptText. Use:
cryptText.append ((char)currentChar);
Update:
Wouldn't bother with the character value manipulation stuff. You're making all sorts of character set assumptions as it is (try running on an IBM i, which uses EBCDIC rather than ASCII, and watch it all break).
Use a lookup table instead:
private static final String in = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final String out = "NOPQRSTUVWXYZABCDEFGHIJKLM";
...
final int idx = in.indexOf (ch);
cryptText.append ((-1 == idx) ? ch : out.charAt (idx));

Related

ASCII conversion

I wanted to convert ASCII values to its corresponding characters so I wrote this simple code:
public class Test {
public static void main(String[] args) {
int i=0;
char ch='c';
for(i=0;i<127;i++)
{
ch=(char)i;
System.out.print(ch+"\t");
}
System.out.println("finish");
}
}
But as output it's showing nothing and along with that the control is not even getting out of the loop though the process gets finished..plz explain this kind of behavior and the right code.
As other people have pointed out, you have included the control characters; if you alter the loop (as below) you get the full set, excluding these control characters:
public static void main() {
for(int i = 33; i < 127; i++)
{
char ch = (char) i;
System.out.print(i + ":" + ch + "\t");
}
System.out.println("finish");
}

Attempts to call a method in the same class not working (java)

I'm creating a random number generator which then sorts the digits from largest to smallest. Initially it worked but then I changed a few things. As far as I'm aware I undid all the changes (ctrl + z) but now I have errors at the points where i try to call the methods. This is probably a very amateur problem but I haven't found an answer. The error i'm met with is "method in class cannot be applied to given types"
Here's my code:
public class RandomMath {
public static void main(String[] args) {
String bigger = bigger(); /*ERROR HERE*/
System.out.println(bigger);
}
//create method for generating random numbers
public static int generator(int n){
Random randomGen = new Random();
//set max int to 10000 as generator works between 0 and n-1
for(int i=0; i<1; i++){
n = randomGen.nextInt(10000);
// exclude 1111, 2222, 3333, 4444, 5555, 6666, 7777, 8888, 9999, 0000
if((n==1111 || n==2222 || n==3333 || n ==4444 || n==5555)
||(n==6666 || n==7777 || n==8888 || n==9999 || n==0000)){
i--;
}
}
return n;
}
//create method for denoting the bigger number
public static String bigger(int generated){
generated = generator(); /*ERROR HERE*/
System.out.println(generated);
int[] times = new int[10];
while (generated != 0) {
int val = generated % 10;
times[val]++;
generated /= 10;
}
String bigger = "";
for (int i = 9; i >= 0; i--) {
for (int j = 0; j < times[i]; j++) {
bigger += i;
}
}
return bigger;
}
}
You have not defined a method bigger(), only bigger(int generated). Therefore, you must call your bigger method with an integer parameter.

Cannot find symbol error with scanner

I'm trying to make this program run, but I have one last error that I can't fix. I get an error message when trying to get user input in my lasTal() function. I am surprised about this error because the exact same line of code has worked for me in my other program.
import java.util.Scanner;
public class Nastaord{
public static int bFinal, cFinal;
public static int[] tallistaFinal;
private static int[] lasTal(){
int[] tallista; //Det vi ska ha talföljden i
int i = 0; //räknare för tallista
while(true){
System.out.print("Ange tal, eller tryck enter om du är klar: ");
String input = scanner.nextLine();
int nytt_tal = Integer.parseInt(input);
if(input == ""){
return tallista;}
tallista[i] = nytt_tal;
i++;
}
}
private static boolean bcFinns(int[] tallista){
boolean OK = true;
for(int b = -9; b <= 9; b++){
for(int c = -9; c <= 9; c++){
for(int i = tallista.length; i > 0;i--){
OK = tallista[i] == tallista[i-1]*b+c;
if(OK == false){
break;}
}
if(OK == true){
bFinal = b;
cFinal = c;
tallistaFinal = tallista;
return true;}
}
}
return false;
}
public static void main(String[] args){
boolean OK = bcFinns(lasTal());
if (OK == true){
System.out.print(tallistaFinal[tallistaFinal.length-1]*bFinal+cFinal);
}
if (OK == false){
System.out.print("No");
}
}
}
This is my error message:
Nastaord.java:13: error: cannot find symbol
String input = scanner.nextLine();
^
symbol: variable scanner
location: class Nastaord
Thanks
you did not creat a Scanner Object. Use this in lasTal() method at starting to take input from keyboard and u need to initialize "tallista " array.
Scanner scanner = new Scanner(System.in);

check palindrome in java code

I'm making a really simple app in java code, but for some reason it doesnt work. its a palindrome checker.
here is the code.
MAIN:
public class main {
public static void main(String[] args) {
Palindroom.palindroomChecker("RACECAR");
}
}
`Palindroom class:
public class Palindroom {
public static void palindroomChecker(String input) {
String omgekeerd = "";
boolean isPalindroom = false;
int length = input.length();
for(int i = 0; i < length; i++ ) {
String hulp = "" + input.charAt(i);
omgekeerd = omgekeerd + hulp;
}
System.out.println(omgekeerd);
System.out.println(input);
if(omgekeerd.equals(input)){
System.out.println("DIT IS EEN PALINDROOM!");
}
else {
System.out.println("HELAAS, DIT IS GEEN PALINDROOM!");
}
}
}`
For some reason the check in the if-statement doesnt go as it has to go. As you can see i checked omgekeerd and input and i also checked earlier the length of omgekeerd to see if there were clear spaces.
Can someone help me out!
thanks in advance
greetings Mauro Palsgraaf
Your logic is flawed. You're reconstructing a new string by appending every char of the input, in the same order, and then check that both strings are equal. So your method always says that the input is a palindrome.
You should construct a new string by appending the chars in the reverse order.
Or you could make it faster by checking that the nth character is the same as the character at the length - 1 - n position, for each n between 0 and length / 2.
You are not actually reversing the string, looks like omgekeerd will be in the same order as input.
Replace for with for(int i = length-1; i >= 0; i--) {
This can be simplified a lot
boolean isPalindrome = new StringBuilder(input).reverse().equals(input);
Maybe this would work for you?
String str = "madam i'm adam."; // String to compare
str = str.replaceAll("[//\\s,',,,.]",""); // Remove special characters
int len = str.length();
boolean isSame = false;
for(int i =0; i<len;i++){
if(str.charAt(i) == str.charAt(len-1-i)){
isSame = true;
}
else{
isSame = false;
break;
}
}
if(isSame){
System.out.print("Equal");
}
else{
System.out.print("Not equal");
}
i=0;
j=str.length()-1; //length of given string
String str; // your input string
while((i<j)||(i!=j)){
if(str.charAt(i)!=str.charAt(j)){
System.out.println("not palindrome");
break;
}
i++;
j--;
}
System.out.print("palindrome");
//this can used for checking without the need of generating and storing a reverse string

How do I use BER encoding with object System.DirectoryServices.Protocols.BerConverter.Encode("???", myData)

I need to encode and decode BER data. .NET has the class System.DirectoryServices.Protocols.BerConverter
The static method requires me to enter a string in the first parameter as shown below
byte[] oid = { 0x30, 0xD, 0x6, 0x9, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0xD, 0x1, 0x1, 0x1, 0x5, 0x0 }; // Object ID for RSA
var result2 = System.DirectoryServices.Protocols.BerConverter.Decoding("?what goes here?", oid);
BER encoding is used in LDAP, Certificates, and is commonplace in many other formats.
I'll be happy with information telling me how to Encode or Decode on this class. There is nothing on Stack Overflow or the first few pages of Google (or Bing) regarding this.
Question
How do I convert the byte array above to the corresponding OID using BER decoding?
How can I parse (or attempt to parse) SubjectPublicKeyInfo ASN.1 data in DER or BER format?
It seems the DER encoding\decoding classes are internal to the .NET framework. If so, where are they? (I'd like to ask connect.microsoft.com to make these members public)
How do I convert the byte array above to the corresponding OID using BER decoding?
After you have extracted the OID byte array, you can convert it to an OID string using OidByteArrayToString(). I have included the code below, since I couldn't find a similar function in the .NET libraries.
How can I parse (or attempt to parse) SubjectPublicKeyInfo ASN.1 data in DER or BER format?
I was not able to find a TLV parser in the .NET SDK either. Below is an implementation of a BER TLV parser, BerTlv. Since DER is a subset of BER, parsing will work the same way. Given a BER-TLV byte[] array, it will return a list of BerTlv objects that support access of sub TLVs.
It seems the DER encoding\decoding classes are internal to the .NET framework. If so, where are they? (I'd like to ask connect.microsoft.com to make these members public)
Maybe somebody else can answer this question.
Summary
Here is an example of how you can use the code provided below. I have used the public key data you provided in your previous post. The BerTlv should probably be augmented to support querying like BerTlv.getValue(rootTlvs, '/30/30/06');.
public static void Main(string[] args)
{
string pubkey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDrEee0Ri4Juz+QfiWYui/E9UGSXau/2P8LjnTD8V4Unn+2FAZVGE3kL23bzeoULYv4PeleB3gfmJiDJOKU3Ns5L4KJAUUHjFwDebt0NP+sBK0VKeTATL2Yr/S3bT/xhy+1xtj4RkdV7fVxTn56Lb4udUnwuxK4V5b5PdOKj/+XcwIDAQAB";
byte[] pubkeyByteArray = Convert.FromBase64String(pubkey);
List<BerTlv> rootTlvs = BerTlv.parseTlv(pubkeyByteArray);
BerTlv firstTlv = rootTlvs.Where(tlv => tlv.Tag == 0x30).First();//first sequence (tag 30)
BerTlv secondTlv = firstTlv.SubTlv.Where(tlv => tlv.Tag == 0x30).First();//second sequence (tag 30)
BerTlv oid = secondTlv.SubTlv.Where(tlv => tlv.Tag == 0x06).First();//OID tag (tag 30)
string strOid = OidByteArrayToString(oid.Value);
Console.WriteLine(strOid);
}
Output:
1.2.840.113549.1.1.1
OID Encode/Decode
public static byte[] OidStringToByteArray(string oid)
{
string[] split = oid.Split('.');
List<byte> retVal = new List<byte>();
//root arc
if (split.Length > 0)
retVal.Add((byte)(Convert.ToInt32(split[0])*40));
//first arc
if (split.Length > 1)
retVal[0] += Convert.ToByte(split[1]);
//subsequent arcs
for (int i = 2; i < split.Length; i++)
{
int arc_value = Convert.ToInt32(split[i]);
Stack<byte> bytes = new Stack<byte>();
while (arc_value != 0)
{
byte val = (byte) ((arc_value & 0x7F) | (bytes.Count == 0 ? 0x0:0x80));
arc_value >>= 7;
bytes.Push(val);
}
retVal.AddRange(bytes);
}
return retVal.ToArray();
}
public static string OidByteArrayToString(byte[] oid)
{
StringBuilder retVal = new StringBuilder();
//first byte
if (oid.Length > 0)
retVal.Append(String.Format("{0}.{1}", oid[0] / 40, oid[0] % 40));
// subsequent bytes
int current_arc = 0;
for (int i = 1; i < oid.Length; i++)
{
current_arc = (current_arc <<= 7) | oid[i] & 0x7F;
//check if last byte of arc value
if ((oid[i] & 0x80) == 0)
{
retVal.Append('.');
retVal.Append(Convert.ToString(current_arc));
current_arc = 0;
}
}
return retVal.ToString();
}
BER-TLV Parser
class BerTlv
{
private int tag;
private int length;
private int valueOffset;
private byte[] rawData;
private List<BerTlv> subTlv;
private BerTlv(int tag, int length, int valueOffset, byte[] rawData)
{
this.tag = tag;
this.length = length;
this.valueOffset = valueOffset;
this.rawData = rawData;
this.subTlv = new List<BerTlv>();
}
public int Tag
{
get { return tag; }
}
public byte[] RawData
{
get { return rawData; }
}
public byte[] Value
{
get
{
byte[] result = new byte[length];
Array.Copy(rawData, valueOffset, result, 0, length);
return result;
}
}
public List<BerTlv> SubTlv
{
get { return subTlv; }
}
public static List<BerTlv> parseTlv(byte[] rawTlv)
{
List<BerTlv> result = new List<BerTlv>();
parseTlv(rawTlv, result);
return result;
}
private static void parseTlv(byte[] rawTlv, List<BerTlv> result)
{
for (int i = 0, start=0; i < rawTlv.Length; start=i)
{
//parse Tag
bool constructed_tlv = (rawTlv[i] & 0x20) != 0;
bool more_bytes = (rawTlv[i] & 0x1F) == 0x1F;
while (more_bytes && (rawTlv[++i] & 0x80) != 0) ;
i++;
int tag = Util.getInt(rawTlv, start, i-start);
//parse Length
bool multiByte_Length = (rawTlv[i] & 0x80) != 0;
int length = multiByte_Length ? Util.getInt(rawTlv, i+1, rawTlv[i] & 0x1F) : rawTlv[i];
i = multiByte_Length ? i + (rawTlv[i] & 0x1F) + 1: i + 1;
i += length;
byte[] rawData = new byte[i - start];
Array.Copy(rawTlv, start, rawData, 0, i - start);
BerTlv tlv = new BerTlv(tag, length, i - length, rawData);
result.Add(tlv);
if (constructed_tlv)
parseTlv(tlv.Value, tlv.subTlv);
}
}
}
Here is a utility class that contains some functions used in the class above. It is included for the sake of clarity how it works.
class Util
{
public static string getHexString(byte[] arr)
{
StringBuilder sb = new StringBuilder(arr.Length * 2);
foreach (byte b in arr)
{
sb.AppendFormat("{0:X2}", b);
}
return sb.ToString();
}
public static byte[] getBytes(String str)
{
byte[] result = new byte[str.Length >> 1];
for (int i = 0; i < result.Length; i++)
{
result[i] = (byte)Convert.ToInt32(str.Substring(i * 2, 2), 16);
}
return result;
}
public static int getInt(byte[] data, int offset, int length)
{
int result = 0;
for (int i = 0; i < length; i++)
{
result = (result << 8) | data[offset + i];
}
return result;
}
}