Chacha Encryption in android using sponge castle - java

I simply want to encrypt and decrypt text in Android using ChaCha20.
I have found some example but can't find a solution to make it in the right way. I want ChaCha encryption. Can someOne guide me how could I achieve it. I tried modifying these code a lot.
SecurityUtil
public class SecurityUtil extends Properties {
public String decrypt(String name, String keyString)
throws Exception {
BlowfishEngine engine = new BlowfishEngine();
PaddedBufferedBlockCipher cipher =
new PaddedBufferedBlockCipher(engine);
StringBuffer result = new StringBuffer();
KeyParameter key = new KeyParameter(keyString.getBytes());
cipher.init(false, key);
byte out[] = Base64.decode(name);
byte out2[] = new byte[cipher.getOutputSize(out.length)];
int len2 = cipher.processBytes(out, 0, out.length, out2, 0);
cipher.doFinal(out2, len2);
String s2 = new String(out2);
for (int i = 0; i < s2.length(); i++) {
char c = s2.charAt(i);
if (c != 0) {
result.append(c);
}
}
return result.toString();
}
public String encrypt(String value, String keyString)
throws Exception {
BlowfishEngine engine = new BlowfishEngine();
PaddedBufferedBlockCipher cipher =
new PaddedBufferedBlockCipher(engine);
KeyParameter key = new KeyParameter(keyString.getBytes());
cipher.init(true, key);
byte in[] = value.getBytes();
byte out[] = new byte[cipher.getOutputSize(in.length)];
int len1 = cipher.processBytes(in, 0, in.length, out, 0);
try {
cipher.doFinal(out, len1);
} catch (CryptoException e) {
e.printStackTrace();
throw new Exception(e.getMessage());
}
String s = new String(Base64.encode(out));
return s;
}
}
I have tried changing BlowfishEngine to ChaChaEngine but It is a class not an interface. And tried a lot more way.
AESWrapper
public class AESWrapper {
public byte[] encrypt(byte[] plainData, byte[] key) throws AESEncryptionFailedException {
PaddedBufferedBlockCipher paddedBufferedBlockCipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), new PKCS7Padding());
ParametersWithRandom params = new ParametersWithRandom(new KeyParameter(key));
paddedBufferedBlockCipher.init(true, params);
byte[] cipherText = new byte[paddedBufferedBlockCipher.getOutputSize(plainData.length)];
int val = paddedBufferedBlockCipher.processBytes(plainData, 0, plainData.length, cipherText, 0);
try {
paddedBufferedBlockCipher.doFinal(cipherText, val);
} catch (DataLengthException e) {
throw new AESEncryptionFailedException("AES Encryption failed due to data length mismatch");
} catch (IllegalStateException e) {
throw new AESEncryptionFailedException("AES Encryption failed");
} catch (InvalidCipherTextException e) {
throw new AESEncryptionFailedException("AES Encryption failed due to invalid cipher text");
}
return cipherText;
}
public byte[] decrypt(byte[] cipherText, byte[] key) throws AESDecryptionFailedException {
PaddedBufferedBlockCipher paddedBufferedBlockCipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), new PKCS7Padding());
ParametersWithRandom params = new ParametersWithRandom(new KeyParameter(key));
paddedBufferedBlockCipher.init(false, params);
byte[] plainText = new byte[paddedBufferedBlockCipher.getOutputSize(cipherText.length)];
int val = paddedBufferedBlockCipher.processBytes(cipherText, 0, cipherText.length, plainText, 0);
try {
int len = paddedBufferedBlockCipher.doFinal(plainText, val);
byte[] decryptedData = new byte[val + len];
System.arraycopy(plainText, 0, decryptedData, 0, len + val);
return decryptedData;
} catch (DataLengthException e) {
throw new AESDecryptionFailedException("AES Decryption failed due to data length mismatch");
} catch (IllegalStateException e) {
throw new AESDecryptionFailedException("AES Decryption failed");
} catch (InvalidCipherTextException e) {
throw new AESDecryptionFailedException("AES Decryption failed due to invalid cipher text");
}
}
}
Is there an easy way to simply encrypt and decrypt text using chacha.

Related

Bouncy Castle Java PGP encryption & decryption

I am trying to implement PGP encryption in Java using Bouncy Castle, also using some of the examples provided by them.
But if I try and decrypt the message I just encrypted, it does not work. The keys and the decryption method seem to be ok, because I can encrypt using an external tool (link) and then successfully decrypt it here.
public static void main(String[] args) throws PGPException, IOException, NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException {
Security.addProvider(new BouncyCastleProvider());
byte[] msg = ("Test blabla BLA").getBytes();
byte[] encData = encrypt(msg, publicKey);
System.out.println(new String(encData));
System.err.println("DECRYPTED");
System.out.println(decrypt(IOUtils.toInputStream(new String(encData), StandardCharsets.UTF_8), privateKey, passphrase));
System.err.println("DECRYPTED external");
String testEncryptedMsg = "-----BEGIN PGP MESSAGE-----\n" +
"Version: BCPG C# v1.6.1.0\n" +
"\n" +
"hQIMA4p9BgtBOg+BARAAiLdmGZBupsSkrji1qdC/y6KACuaWytcjVg3LWudWRlH8\n" +
"Ye1U0bz+HYc6mLt21RivAZ3p+lPXPzh/h0GVLW/aI2ngJracL+iEA7eam5/H3NQV\n" +
"2o0CR1mjw4xOf0XwDxaLrnivdeuWniXiZyFN7Ud7lmNG+EmQ0d5ZfR7KEnTJNjSe\n" +
"FpzwRffBG5lKB4CxF49jBp+Iupdv4A5JzHuDVBkypPMNhS/UEbuPOt5cfmddYVvW\n" +
"gtDM3rX+ePBhg7d/mVkiDT2KM0Cr7GSrdZ8q83fF4sat3Xp8OHMq61GWriNK4gwb\n" +
"ViT/vmEsY0n55TVgN5VagMZJJlEThkqWE2wpEjq4HM8pNxR4PvP5inqP5oipn8Os\n" +
"Nq2a5f77BS7GB9NQ+hnaLSBsywJkZVKqygN81MeHBnNrVXFQ/Hqg24BLwk49bOuH\n" +
"jTUzorudCnjj/p8/WiyR+PuESkQDLKpo1z9KGEE/rKjTqAwH/fBKJ73XpmAWwd4U\n" +
"1hv/EdF+XDZv7XwxeVjSIK2inAjdNz+way1WNY3qouo7G+gjKf1gbL14q2HVPnd/\n" +
"7mfiW3uWCQ7GhXlHtd1E0WeK2296TdBuSGAvLlVxI4xepsiuVw+zC4BxvAkTXB/a\n" +
"HyJZhKPksHMRCt8ZxitMfhdvMNGjc4MDhv1MLqKijpagKhgrmDTiJRMb3ng6QLvJ\n" +
"L2GICyuS4aIsz6XiCQvZG8ebfb0J4uogbb5HxS2fGFT+Y/VgpCnwhwj6LnLBy1Q3\n" +
"=D/1d\n" +
"-----END PGP MESSAGE-----\n";
System.out.println(decrypt(IOUtils.toInputStream(testEncryptedMsg, StandardCharsets.UTF_8), privateKey, passphrase));
}
I think the problem is on the encryption side, but I cannot figure out what exactly it is. Does anyone have any ideas?
public static byte[] encrypt(byte[] bytes, String publicKey) throws IOException {
ByteArrayOutputStream encOut = new ByteArrayOutputStream();
try {
PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(
new JcePGPDataEncryptorBuilder(PGPEncryptedData.AES_128)
.setSecureRandom(new SecureRandom())
.setWithIntegrityPacket(true)
.setProvider("BC"));
PGPPublicKey encryptionKey = readPublicKey(publicKey);
encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(encryptionKey).setProvider("BC"));
ArmoredOutputStream aOut = new ArmoredOutputStream(encOut);
OutputStream cOut = encGen.open(aOut, bytes.length);
// write out the literal data
PGPLiteralDataGenerator lData = new PGPLiteralDataGenerator();
OutputStream pOut = lData.open(aOut, PGPLiteralData.UTF8, PGPLiteralData.CONSOLE, bytes.length, new Date());
pOut.write(bytes);
pOut.close();
// finish the encryption
cOut.close();
aOut.close();
} catch (PGPException e) {
log.error("Exception encountered while encoding data.", e);
}
return encOut.toByteArray();
}
public static String decrypt(InputStream in, String secretKey, String passphrase) throws IOException {
String content = null;
try {
in = PGPUtil.getDecoderStream(in);
JcaPGPObjectFactory pgpF = new JcaPGPObjectFactory(in);
PGPEncryptedDataList enc;
Object o = pgpF.nextObject();
// the first object might be a PGP marker packet.
if (o instanceof PGPEncryptedDataList) {
enc = (PGPEncryptedDataList) o;
} else {
enc = (PGPEncryptedDataList) pgpF.nextObject();
}
// find the secret key
Iterator<PGPEncryptedData> it = enc.getEncryptedDataObjects();
PGPPrivateKey sKey = null;
PGPPublicKeyEncryptedData pbe = null;
PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(new ByteArrayInputStream(secretKey.getBytes())), new JcaKeyFingerprintCalculator());
while (sKey == null && it.hasNext()) {
pbe = (PGPPublicKeyEncryptedData) it.next();
sKey = findSecretKey(pgpSec, pbe.getKeyID(), passphrase.toCharArray());
}
if (sKey == null) {
log.error("Secret key for message not found.");
throw new IllegalArgumentException("secret key for message not found.");
}
InputStream clear = pbe.getDataStream(new JcePublicKeyDataDecryptorFactoryBuilder().setProvider("BC").build(sKey));
JcaPGPObjectFactory plainFact = new JcaPGPObjectFactory(clear);
Object message = plainFact.nextObject();
if (message instanceof PGPCompressedData) {
PGPCompressedData cData = (PGPCompressedData) message;
JcaPGPObjectFactory pgpFact = new JcaPGPObjectFactory(cData.getDataStream());
message = pgpFact.nextObject();
}
if (message instanceof PGPLiteralData) {
PGPLiteralData ld = (PGPLiteralData) message;
content = new String(ld.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
} else if (message instanceof PGPOnePassSignatureList) {
throw new PGPException("encrypted message contains a signed message - not literal data.");
} else {
throw new PGPException("message is not a simple encrypted file - type unknown.");
}
if (pbe.isIntegrityProtected()) {
if (!pbe.verify()) {
log.error("message failed integrity check");
} else {
log.info("message integrity check passed");
}
} else {
log.warn("no message integrity check");
}
} catch (PGPException e) {
log.error("Exception encountered while decrypting file.", e);
}
return content;
}
private static PGPPrivateKey findSecretKey(PGPSecretKeyRingCollection pgpSec, long keyID, char[] pass) throws PGPException {
PGPSecretKey pgpSecKey = pgpSec.getSecretKey(keyID);
if (pgpSecKey == null) {
return null;
}
return pgpSecKey.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(pass));
}
private static PGPPublicKey readPublicKey(String publicKey) throws IOException, PGPException {
InputStream input = IOUtils.toInputStream(publicKey, StandardCharsets.UTF_8);
PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(input), new JcaKeyFingerprintCalculator());
Iterator<PGPPublicKeyRing> keyRingIter = pgpPub.getKeyRings();
while (keyRingIter.hasNext()) {
PGPPublicKeyRing keyRing = keyRingIter.next();
Iterator<PGPPublicKey> keyIter = keyRing.getPublicKeys();
while (keyIter.hasNext()) {
PGPPublicKey key = keyIter.next();
if (key.isEncryptionKey()) {
return key;
}
}
}
throw new IllegalArgumentException("Can't find encryption key in key ring.");
}
Here is the encryption method that eventually worked for me.
It helped debugging together with the examples provided by the BCFipsIn100 book.
public byte[] encrypt(byte[] bytes, String publicKey) throws IOException {
try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
byte[] compressedData = compress(bytes);
PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(
new JcePGPDataEncryptorBuilder(PGPEncryptedData.CAST5)
.setWithIntegrityPacket(true)
.setSecureRandom(new SecureRandom())
.setProvider(PROVIDER));
PGPPublicKey encryptionKey = readPublicKey(publicKey);
encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(encryptionKey).setProvider(PROVIDER));
ArmoredOutputStream aOut = new ArmoredOutputStream(byteArrayOutputStream);
OutputStream cOut = encGen.open(aOut, compressedData.length);
cOut.write(compressedData);
cOut.close();
aOut.close();
return byteArrayOutputStream.toByteArray();
} catch (PGPException e) {
log.error("Exception encountered while encoding data.", e);
}
return new byte[0];
}
private static byte[] compress(byte[] clearData) throws IOException {
try (ByteArrayOutputStream bOut = new ByteArrayOutputStream()) {
PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(CompressionAlgorithmTags.ZIP);
OutputStream cos = comData.open(bOut);
PGPLiteralDataGenerator lData = new PGPLiteralDataGenerator();
OutputStream pOut = lData.open(cos,
PGPLiteralData.BINARY,
PGPLiteralData.CONSOLE,
clearData.length,
new Date());
pOut.write(clearData);
pOut.close();
comData.close();
return bOut.toByteArray();
}
}
There are some errors in your encrypt() method code:
First and foremost, in this line your are opening the literal data stream directly on your armored output stream, while you should open it on your encryption stream:
OutputStream pOut = lData.open(aOut, PGPLiteralData.UTF8, PGPLiteralData.CONSOLE, bytes.length, new Date());
// replace with
OutputStream pOut = lData.open(cOut, PGPLiteralData.UTF8, PGPLiteralData.CONSOLE, bytes.length, new Date());
Furthermore you should replace the line
OutputStream cOut = encGen.open(aOut, bytes.length);
// with
OutputStream cOut = encGen.open(aOut, new byte[1<<9]);
Otherwise you will run into encoding issues.
These changes should make your code run.
I however recommend using a library such as PGPainless (disclaimer: author here) which does all the low level stream wrapping and checking for you. On top of that it does proper signature verification, which most other Bouncycastle based libraries lack.

javax.crypto.BadPaddingException: Decryption error

Here is the error I have got when run my Encode & Decode Class.
javax.crypto.BadPaddingException: Decryption error
at sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:380)
at sun.security.rsa.RSAPadding.unpad(RSAPadding.java:291)
at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:365)
at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:391)
at javax.crypto.Cipher.doFinal(Cipher.java:2087)
at RSAEncDecDemo.decryptData(RSAEncDecDemo.java:64)
at RSAEncDecDemo.main(RSAEncDecDemo.java:47)
java.lang.NullPointerException
at java.lang.String.<init>(String.java:556)
at RSAEncDecDemo.decryptData(RSAEncDecDemo.java:70)
at RSAEncDecDemo.main(RSAEncDecDemo.java:47)
Here is the source code of RSAEncDecDemo.java class file.
public class RSAEncDecDemo {
private static final String PUBLIC_KEY_FILE = "lk.public.key";
private static final String PRIVATE_KEY_FILE = "lk.private.key";
#SuppressWarnings("restriction")
public static void main(String[] args) throws IOException {
try {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
writeStringkey(PUBLIC_KEY_FILE,new BASE64Encoder().encode(publicKey.getEncoded()));
writeStringkey(PRIVATE_KEY_FILE,new BASE64Encoder().encode(privateKey.getEncoded()));
String demoString = "123346";
RSAEncDecDemo rsa = new RSAEncDecDemo();
String decrypted = rsa.decryptData(demoString);
String msisdn = decrypted.substring(0,decrypted.indexOf("|"));
} catch (Exception e) {
e.printStackTrace();
}
}
private String decryptData(String strData) throws IOException {
byte[] data = DatatypeConverter.parseHexBinary(strData);
byte[] descryptedData = null;
try {
PrivateKey privateKey = readPrivateKeyFromFile(PRIVATE_KEY_FILE);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
descryptedData = cipher.doFinal(data);
} catch (Exception e) {
e.printStackTrace();
}
return new String(descryptedData);
}
#SuppressWarnings("restriction")
public PrivateKey readPrivateKeyFromFile(String fileName)throws IOException, NoSuchAlgorithmException,InvalidKeySpecException {
String publicK = readStringKey(fileName);
byte[] keyBytes = new BASE64Decoder().decodeBuffer(publicK);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory fact = KeyFactory.getInstance("RSA");
return fact.generatePrivate(keySpec);
}
public PrivateKey readPrivateKeyFromFileold(String fileName)throws IOException {
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream(new File(fileName));
ois = new ObjectInputStream(fis);
BigInteger modulus = (BigInteger) ois.readObject();
BigInteger exponent = (BigInteger) ois.readObject();
RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec(modulus, exponent);
KeyFactory fact = KeyFactory.getInstance("RSA");
PrivateKey privateKey = fact.generatePrivate(rsaPrivateKeySpec);
return privateKey;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ois != null) {
ois.close();
if (fis != null) {
fis.close();
}
}
}
return null;
}
public static void writeStringkey(String fileName, String data) {
try {
FileWriter out = new FileWriter(new File(fileName));
out.write(data);
out.close();
} catch (IOException e) {
}
}
public static String readStringKey(String fileName) {
BufferedReader reader = null;
StringBuffer fileData = null;
try {
fileData = new StringBuffer(2048);
reader = new BufferedReader(new FileReader(fileName));
char[] buf = new char[1024];
int numRead = 0;
while ((numRead = reader.read(buf)) != -1) {
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
buf = new char[1024];
}
reader.close();
} catch (Exception e) {
} finally {
if (reader != null) {
reader = null;
}
}
return fileData.toString();
}
}
Where is mistaken point.? Decryption part is give that error.
Whole class uploaded here
LINK TO SOURCE CODE
-Thanks
In principle a ciphertext should be indistinguishable from random. That said, ciphers do place constraints on the domain (size and possible values). In the case of RSA PKCS#1 - which is the default mode for "RSA" within the Oracle provider - the output must be precisely the key size (in bytes). Furthermore, the value must be smaller than the modulus.
Now assume that you've just shown us a demo value (because the exception doesn't match the input) and the size of the ciphertext is correct. In that case you would get an unpadding exception when either:
the private key doesn't match the public key used;
the wrong padding mode (e.g. OAEP) was used to create the ciphertext;
the ciphertext was altered (e.g. due to an invalid conversion to a string).
You would have to try until you find the culprit, without the required information we cannot test this for you.

C# server with java/c# clients, aes256 encryption and decryption

So I have my c# server program and a working c# client, now I want to use java for linux and mac clients.
So when the application starts it will request the current encryption/decryption key from the server, which will be used for communication encryption.
But since I'm very new to java, I dont really know how to get it working, code is very different, I have the following code for my java client:
public class CryptoClass
{
static String IV = "AAAAAAAAAAAAAAAA";
public static byte[] encrypt(String plainText, String encryptionKey) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", "SunJCE");
SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), "AES");
cipher.init(Cipher.ENCRYPT_MODE, key,new IvParameterSpec(IV.getBytes("UTF-8")));
return cipher.doFinal(plainText.getBytes("UTF-8"));
}
public static String decrypt(byte[] cipherText, String encryptionKey) throws Exception{
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", "SunJCE");
SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), "AES");
cipher.init(Cipher.DECRYPT_MODE, key,new IvParameterSpec(IV.getBytes("UTF-8")));
return new String(cipher.doFinal(cipherText),"UTF-8");
}
}
and this is the code for the c# client
public byte[] AES_Decrypt(byte[] bytesToBeDecrypted, byte[] passwordBytes)
{
byte[] decryptedBytes = null;
byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
using (MemoryStream ms = new MemoryStream())
{
using (RijndaelManaged AES = new RijndaelManaged())
{
AES.KeySize = 256;
AES.BlockSize = 128;
var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);
AES.Mode = CipherMode.CFB;
AES.Padding = PaddingMode.PKCS7;
using (var cs = new CryptoStream(ms, AES.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length);
cs.Close();
}
decryptedBytes = ms.ToArray();
}
}
return decryptedBytes;
}
public byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes)
{
byte[] encryptedBytes = null;
byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
using (MemoryStream ms = new MemoryStream())
{
using (RijndaelManaged AES = new RijndaelManaged())
{
AES.KeySize = 256;
AES.BlockSize = 128;
var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);
AES.Mode = CipherMode.CFB;
AES.Padding = PaddingMode.PKCS7;
using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
cs.Close();
}
encryptedBytes = ms.ToArray();
}
}
return encryptedBytes;
}
Thanks in advance
I fixed it, I changed my java code to this:
public class CryptoClass {
private static final String AES_CBC_PKCS5PADDING = "AES/CBC/PKCS5PADDING";
private static final int KEY_SIZE = 256;
public String DecryptText(String input) throws NoSuchAlgorithmException
{
input = input.replace("\0", "");
byte[] bytesToBeDecrypted = input.getBytes();
byte[] passwordBytes = Config.ServerKey.getBytes();
MessageDigest md = MessageDigest.getInstance("SHA-256");
passwordBytes = md.digest(passwordBytes);
byte[] bytesDecrypted = null;
try {
bytesDecrypted = AES_Decrypt(bytesToBeDecrypted, passwordBytes);
} catch (IllegalBlockSizeException ex) {
Logger.getLogger(CryptoClass.class.getName()).log(Level.SEVERE, null, ex);
} catch (BadPaddingException ex) {
Logger.getLogger(CryptoClass.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidKeyException ex) {
Logger.getLogger(CryptoClass.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidAlgorithmParameterException ex) {
Logger.getLogger(CryptoClass.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchPaddingException ex) {
Logger.getLogger(CryptoClass.class.getName()).log(Level.SEVERE, null, ex);
}
return new String(bytesDecrypted);
}
public String EncryptText(String input) throws NoSuchAlgorithmException
{
byte[] bytesToBeEncrypted = input.getBytes();
byte[] passwordBytes = Config.ServerKey.getBytes();
MessageDigest md = MessageDigest.getInstance("SHA-256");
passwordBytes = md.digest(passwordBytes);
byte[] bytesEncrypted = null;
try {
bytesEncrypted = AES_Encrypt(bytesToBeEncrypted, passwordBytes);
} catch (NoSuchPaddingException ex) {
Logger.getLogger(CryptoClass.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidAlgorithmParameterException ex) {
Logger.getLogger(CryptoClass.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidKeyException ex) {
Logger.getLogger(CryptoClass.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalBlockSizeException ex) {
Logger.getLogger(CryptoClass.class.getName()).log(Level.SEVERE, null, ex);
} catch (BadPaddingException ex) {
Logger.getLogger(CryptoClass.class.getName()).log(Level.SEVERE, null, ex);
}
return Base64.getEncoder().encodeToString(bytesEncrypted);
}
public byte[] AES_Decrypt(byte[] bytesToBeDecrypted, byte[] passwordBytes) throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchPaddingException
{
byte[] decryptedBytes = null;
byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
final Cipher cipher = Cipher.getInstance(AES_CBC_PKCS5PADDING);
final byte[] keyData = Arrays.copyOf(passwordBytes, KEY_SIZE
/ Byte.SIZE);
final byte[] ivBytes = Arrays.copyOf(keyData, cipher.getBlockSize());
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(keyData, "AES"),
new IvParameterSpec(ivBytes));
decryptedBytes = cipher.doFinal(bytesToBeDecrypted);
return decryptedBytes;
}
public byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException
{
byte[] encryptedBytes = null;
byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
final Cipher cipher = Cipher.getInstance(AES_CBC_PKCS5PADDING);
final byte[] keyData = Arrays.copyOf(passwordBytes, KEY_SIZE
/ Byte.SIZE);
final byte[] ivBytes = Arrays.copyOf(keyData, cipher.getBlockSize());
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyData, "AES"),
new IvParameterSpec(ivBytes));
encryptedBytes = cipher.doFinal(bytesToBeEncrypted);
return encryptedBytes;
}

javax.crypto.BadPaddingException: Given final block not properly padded DES

I get error when I try to decode.
This is Decoder:
public class Encrypter {
Cipher ecipher;
Cipher dcipher;
SecretKeySpec key = new SecretKeySpec("missyou1".getBytes(), "DES");
public DesEncrypter() throws Exception {
ecipher = Cipher.getInstance("DES");
dcipher = Cipher.getInstance("DES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
dcipher.init(Cipher.DECRYPT_MODE, key);
}
public String encrypt(String str) throws Exception {
byte[] utf8 = str.getBytes("UTF8");
byte[] enc = ecipher.doFinal(utf8);
return new sun.misc.BASE64Encoder().encode(enc);
}
public String decrypt(String str) throws Exception {
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
byte[] asd = new byte[(dec.length/8+1)*8];
for(int i = 0; i < dec.length; i++){
asd[i] = dec[i];
}
byte[] utf8 = dcipher.doFinal(asd);
return new String(utf8, "UTF8");
}
}
This is code where I get error:
private static void appenda(Encrypter encrypt) {
if (Files.exists(Paths.get(filePath), new LinkOption[] { LinkOption.NOFOLLOW_LINKS })) {
Stream<String> stringStream = null;
try {
stringStream = Files.lines(Paths.get(filePath), StandardCharsets.UTF_8);
} catch (IOException e) {
LOGGER.error("Failed ", e);
}
if (stringStream.toString() != null) {
stringStream.forEach(s -> {
try {
System.out.println(encrypt.decrypt(s));
endpoint.delete(0, endpoint.length());
endpoint.append(encrypt.decrypt(s));
} catch (Exception e) {
LOGGER.error("Failed to decrypt", e);
}
});
}
}
}
in line endpoint.append(encrypter.decrypt(s));
Any idea why?
Its not working because you are needlessly copying the data into an incorrectly sized array.
Just remove the array copy and decrypt the bytes directly.
public String decrypt(String str) throws Exception {
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
byte[] utf8 = dcipher.doFinal(dec);
return new String(utf8, "UTF8");
}

Bouncy Castle J2ME load existing private key

I have a PEM or DER private key, an existing key. How can I load this key with
PrivateKeyFactory.createKey or into an AsymmetricCipherKeyPair ?
I tried this:
InputStream inKey = getClass().getResourceAsStream("/samsjava/user_key_pk8.der");
byte[] binKey = new byte[inKey.available()];
inKey.read(binKey, 0, binKey.length);
inKey.close();
privKey = PrivateKeyFactory.createKey(binKey);
keyPair = new AsymmetricCipherKeyPair(new AsymmetricKeyParameter(false), privKey);
rsaPriv = (RSAPrivateCrtKeyParameters)keyPair.getPrivate();
rsaPub = (RSAPrivateCrtKeyParameters)keyPair.getPublic();
What can I try next?
I tried the thing in Java, which should get me on the right track for J2ME. Here is the code:
public class EncrypDecrypt {
private RSAPrivateCrtKey rsaPriv;
private RSAPublicKey rsaPub;
private BASE64Decoder decoder;
private BASE64Encoder encoder;
public EncrypDecrypt(){
decoder = new BASE64Decoder();
encoder = new BASE64Encoder();
byte[] buffer;
try {
FileInputStream in = new FileInputStream("pathtofile.pfx");
KeyStore kStore = KeyStore.getInstance("PKCS12");
kStore.load(in, null);
PrivateKey privKeyEntry = (PrivateKey)kStore.getKey("Key Alias", null);
rsaPriv = (RSAPrivateCrtKey) privKeyEntry;
} catch (Exception ex) {
Logger.getLogger(EncrypDecrypt.class.getName()).log(Level.SEVERE, null, ex);
}
}
public String encrypt(String data){
try{
AsymmetricBlockCipher eng = new RSAEngine();
eng = new PKCS1Encoding(eng);
RSAKeyParameters publicKey = new RSAKeyParameters(true, rsaPriv.getModulus(), rsaPriv.getPublicExponent());
eng.init(true, publicKey);
byte[] encrypted = eng.processBlock(data.getBytes(), 0, data.getBytes().length);
return encoder.encode(encrypted);
}
catch(Exception err){
return "";
}
}
public String decrypt(String data){
try
{
byte[] encrypted = decoder.decodeBuffer(data);
AsymmetricBlockCipher eng = new RSAEngine();
eng = new PKCS1Encoding(eng);
RSAKeyParameters privateKey = new RSAKeyParameters(true, rsaPriv.getModulus(), rsaPriv.getPrivateExponent());
eng.init(false, privateKey);
byte[] decrypted = eng.processBlock(encrypted, 0, encrypted.length);
return new String(decrypted);
}
catch(Exception err){
return "";
}
}
}

Categories

Resources