Error while using RSA encryption on BlackBerry - blackberry

I'm trying to use RSA encryption on Blackberry with their native API's. I made a public/private key pair in Java and saved the Modulus and Exponents of the keys as strings so i can generate the keys from this for encryption and decryption. The following code is from the client side and i'm getting a InvalidKeyException and the backtrace is null so I don't know what's happening:
public byte[] Encrypt(byte[] data)
{
try {
RSACryptoSystem cryptoSystem = new RSACryptoSystem(1024);
RSAPublicKey publicKey = new RSAPublicKey(cryptoSystem, _publicKeyExponent.getBytes(), _publicKeyModulus.getBytes());
RSAEncryptorEngine encryptorEngine = new RSAEncryptorEngine(publicKey);
PKCS5FormatterEngine formatterEngine = new PKCS5FormatterEngine( encryptorEngine );
ByteArrayOutputStream output = new ByteArrayOutputStream();
BlockEncryptor encryptor = new BlockEncryptor( formatterEngine, output );
encryptor.write(data);
encryptor.close();
output.close();
return output.toByteArray();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
System.out.println();
e.printStackTrace();
} catch (CryptoTokenException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (CryptoUnsupportedOperationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedCryptoSystemException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
And this is what i did server side to generate my keys:
try {
keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024);
keyFactory = KeyFactory.getInstance("RSA");
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(EncryptorDecryptor.class.getName()).log(Level.SEVERE, null, ex);
}
keyPair = keyPairGenerator.generateKeyPair();
publicKey = keyPair.getPublic();
privateKey = keyPair.getPrivate();
try {
publicKeySpec = keyFactory.getKeySpec(publicKey, RSAPublicKeySpec.class);
privateKeySpec = keyFactory.getKeySpec(privateKey, RSAPrivateKeySpec.class);
} catch (InvalidKeySpecException ex) {
Logger.getLogger(EncryptorDecryptor.class.getName()).log(Level.SEVERE, null, ex);
}
privateKeyModulus = privateKeySpec.getModulus().toString();
privateKeyExponent = privateKeySpec.getPrivateExponent().toString();
publicKeyModulus = publicKeySpec.getModulus().toString();
publicKeyExponent = publicKeySpec.getPublicExponent().toString();
Any ideas?
EDIT: i tried doing a simple test on the server by encrypting and decrypting there and when when I try to decrypt I get a IllegalBlockSizeException these are my encrytion and decryption methods (server side):
public byte[] Decrypt(byte[] data)
{
try {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] cipherData = cipher.doFinal(data);
return cipherData;
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(EncryptorDecryptor.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchPaddingException ex) {
Logger.getLogger(EncryptorDecryptor.class.getName()).log(Level.SEVERE, null, ex);
} catch(IllegalBlockSizeException ex) {
Logger.getLogger(EncryptorDecryptor.class.getName()).log(Level.SEVERE, null, ex);
} catch(InvalidKeyException ex) {
Logger.getLogger(EncryptorDecryptor.class.getName()).log(Level.SEVERE, null, ex);
} catch(BadPaddingException ex) {
Logger.getLogger(EncryptorDecryptor.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
public byte[] Encrypt(byte[] data)
{
try {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] cipherData = cipher.doFinal(data);
return cipherData;
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(EncryptorDecryptor.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchPaddingException ex) {
Logger.getLogger(EncryptorDecryptor.class.getName()).log(Level.SEVERE, null, ex);
} catch(IllegalBlockSizeException ex) {
Logger.getLogger(EncryptorDecryptor.class.getName()).log(Level.SEVERE, null, ex);
} catch(InvalidKeyException ex) {
Logger.getLogger(EncryptorDecryptor.class.getName()).log(Level.SEVERE, null, ex);
} catch(BadPaddingException ex) {
Logger.getLogger(EncryptorDecryptor.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
And this is the simple test i'm trying:
userName = Base64.encode(encryptorDecryptor.Encrypt(userName.getBytes()));
password = Base64.encode(encryptorDecryptor.Encrypt(password.getBytes()));
userName = new String(encryptorDecryptor.Decrypt(Base64.decode(userName)));
password = new String(encryptorDecryptor.Decrypt(Base64.decode(password)));

It is a bug to use String as a container for arbitrary random bytes, e.g. userName = new String(encryptorDecryptor.Encrypt(userName.getBytes()));
is wrong.
I'm not familiar with Blackberry's Java API but in usually you cannot encrypt more than one block with RSA
the toString() methods on arrays (e.g. publicKeySpec.getModulus().toString()) don't return anything useful. You should be able to figure this out just by looking at the data. This is really a beginner java mistake more than a cryptography issue.
Don't using the default character set for the String constructor and String.getBytes() methods. Always specify a character set, usually "UTF-8" is perfect.
That's all I had the patience for.

Related

when use mina-sshd to execute command ,timeout occurred,how can i deal with it

Here follows is my code,how can i deal with it
public ConnectResponse runCommand(UserInfo userInfo, String command, long timeout) {
SshClient sshClient = SshClient.setUpDefaultClient();
sshClient.start();
ChannelExec execChannel = null;
try (ClientSession session = sshClient
.connect(userInfo.getUsername(), userInfo.getTargetIp(), 22)
.verify(CLIENT_VERIFY_TIMEOUT)
.getClientSession();) {
session.addPasswordIdentity(userInfo.getAuthentication());
session.auth().verify(SESSION_VERIFY_TIMEOUT);
execChannel = session.createExecChannel(command);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayOutputStream err = new ByteArrayOutputStream();
execChannel.setOut(out);
execChannel.setErr(err);
execChannel.open();
Set<ClientChannelEvent> events = execChannel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(timeout));
session.close(false);
if (events.contains(ClientChannelEvent.TIMEOUT)) {
throw new BusinessException(500, String.format("执行命令 {%s} 超时了!", command));
}
return new ConnectResponse(out.toString(), err.toString(), execChannel.getExitStatus());
} catch (Exception e) {
throw new BusinessException(e.getCause(), 500, String.format("执行命令 {%s} 出现了一行了!", command));
} finally {
if (!Objects.isNull(execChannel)) {
try {
execChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

How to get a BareJid in smack 4.2.0

I used Roster to create Roster Entry by Roster's method createEntry(BareJid user, String name, String[] groups),but I don't know how to get a BareJid. Anybody could help me?Here are my code,my userJid is a String:
Roster roster = XmppConnectionManager.getInstance().getRoster();
if (roster != null) {
try {
// String[] jids = userJid.split("#");
roster.createEntry(userJid, nickname, null);
} catch (SmackException.NotLoggedInException e) {
e.printStackTrace();
} catch (SmackException.NoResponseException e) {
e.printStackTrace();
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
Log.w(TAG,"roster is null");
}
I just found it by Google, there is a JID helper class JidCreate:
JidCreate.bareFrom(userJid)

how to extract main text from html using Tika

I just want to know that how i can extract main text and plain text from html using Tika?
maybe one possible solution is to use BoilerPipeContentHandler but do you have some sample/demo codes to show it?
thanks very much in advance
The BodyContentHandler class doesn't use the Boilerpipe code, so you'll have to explicitly use the BoilerPipeContentHandler. The following code worked for me:
public String[] tika_autoParser() {
String[] result = new String[3];
try {
InputStream input = new FileInputStream(new File("test.html"));
ContentHandler textHandler = new BodyContentHandler();
Metadata metadata = new Metadata();
AutoDetectParser parser = new AutoDetectParser();
ParseContext context = new ParseContext();
parser.parse(input, new BoilerpipeContentHandler(textHandler), metadata, context);
result[0] = "Title: " + metadata.get(metadata.TITLE);
result[1] = "Body: " + textHandler.toString();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (TikaException e) {
e.printStackTrace();
}
return result;
}
Here is a sample:
public String[] tika_autoParser() {
String[] result = new String[3];
try {
InputStream input = new FileInputStream(new File("/Users/nazanin/Books/Web crawler.pdf"));
ContentHandler textHandler = new BodyContentHandler();
Metadata metadata = new Metadata();
AutoDetectParser parser = new AutoDetectParser();
ParseContext context = new ParseContext();
parser.parse(input, textHandler, metadata, context);
result[0] = "Title: " + metadata.get(metadata.TITLE);
result[1] = "Body: " + textHandler.toString();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (TikaException e) {
e.printStackTrace();
}
return result;
}

Blackberry - send sms timeout

I have simple code to send sms. It works fine. Just little problem. How can I figure out that sms can not be send? Some timeout for Connection or other way? Let's say if there is no network, no sim card or no credit. Thanks
Here is code:
public static void sendSMS(String content, String number) {
MessageConnection mc = null;
TextMessage msg;
try {
mc = (MessageConnection) Connector.open("sms://" + number,Connector.WRITE,true);
msg = (TextMessage) mc.newMessage(MessageConnection.TEXT_MESSAGE);
msg.setPayloadText(content);
mc.send(msg);
} catch (final Exception e) {
e.printStackTrace();
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert(e.getMessage());
}
});
} finally {
try {
if (mc != null) {
mc.close();
}
} catch (IOException e) {
}
}
}
private void sendSMS(final String no, final String msg) {
try {
new Thread() {
public void run() {
if (RadioInfo.getNetworkType() == RadioInfo.NETWORK_CDMA) {
DatagramConnection dc = null;
try {
dc = (DatagramConnection) Connector.open("sms://" + no);
byte[] data = msg.getBytes();
Datagram dg = dc.newDatagram(dc.getMaximumLength());
dg.setData(data, 0, data.length);
dc.send(dg);
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
try {
System.out.println("Message Sent Successfully : Datagram");
Dialog.alert("Message Sent Successfully");
} catch (Exception e) {
System.out.println("Exception **1 : " + e.toString());
e.printStackTrace();
}
}
});
} catch (Exception e) {
System.out.println("Exception 1 : " + e.toString());
e.printStackTrace();
} finally {
try {
dc.close();
dc = null;
} catch (IOException e) {
System.out.println("Exception 2 : " + e.toString());
e.printStackTrace();
}
}
} else {
MessageConnection conn = null;
try {
conn = (MessageConnection) Connector.open("sms://" + no);
//generate a new text message
TextMessage tmsg = (TextMessage) conn.newMessage(MessageConnection.TEXT_MESSAGE);
//set the message text and the address
tmsg.setAddress("sms://" + no);
tmsg.setPayloadText(msg);
//finally send our message
conn.send(tmsg);
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
try {
System.out.println("Message Sent Successfully : TextMessage");
Dialog.alert("Message Sent Successfully : TextMessage");
} catch (Exception e) {
System.out.println("Exception **1 : " + e.toString());
e.printStackTrace();
}
}
});
} catch (Exception e) {
System.out.println("Exception 3 : " + e.toString());
e.printStackTrace();
} finally {
try {
conn.close();
conn = null;
} catch (IOException e) {
System.out.println("Exception 4 : " + e.toString());
e.printStackTrace();
}
}
}
}
}.start();
} catch (Exception e) {
System.out.println("Exception 5 : " + e.toString());
e.printStackTrace();
}

RSA Padding with Bouncy Castle on BlackBerry

I'm using Bouncy Castle to encrypt strings to send them to my java web service where they are decrypted, when the message reaches the server I get a BadPaddingException, anybody know how to properly add the padding to an RSA Cipher with Bouncy Castle on J2ME?
This is the encryption code on the client:
public byte[] Encrypt(byte[] data)
{
RSAKeyParameters publicKey = new RSAKeyParameters(false, new BigInteger(_publicKeyModulus), new BigInteger(_publicKeyExponent));
RSAEngine engine = new RSAEngine();
engine.init(true, publicKey);
byte[] output = engine.processBlock(data, 0, data.length);
return output;
}
And this is how I decrypt it server side:
public byte[] Decrypt(byte[] data)
{
try {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] cipherData = cipher.doFinal(data);
return cipherData;
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(EncryptorDecryptor.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchPaddingException ex) {
Logger.getLogger(EncryptorDecryptor.class.getName()).log(Level.SEVERE, null, ex);
} catch(IllegalBlockSizeException ex) {
Logger.getLogger(EncryptorDecryptor.class.getName()).log(Level.SEVERE, null, ex);
} catch(InvalidKeyException ex) {
Logger.getLogger(EncryptorDecryptor.class.getName()).log(Level.SEVERE, null, ex);
} catch(BadPaddingException ex) {
Logger.getLogger(EncryptorDecryptor.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
Instead of using RSAEngine directly use the PKCS1Encoding class and construct it with
PKCS1Encoding engine = new PKCS1Encoding(new RSAEngine());

Resources