I have written the following code to create a key pair, store the private key locally, and then read the private key from that file.
When I try to call the methods savePrivateKey(); and retrievePrivateKey(); from testData(View view) I get an error that says (String[]) cannot be applied to (). I want to be able to call both of the above mentioned functions in testData(View view);
public class EncryptionActivity extends ActionBarActivity {
private static final String TAG = EncryptionActivity.class.getSimpleName();
TextView textPublicKey;
TextView textPrivateKey;
Button buttonTest;
TextView privateKey;
Integer n;
String FILENAME = "privateKey";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_encryption);
// output keys to screen
textPrivateKey = (TextView)findViewById(R.id.textPrivateKey);
textPrivateKey.setMovementMethod(new ScrollingMovementMethod());
// textPublicKey = (TextView)findViewById(R.id.textPublicKey);
}
private void AsymmetricAlgorithmRSA() {
// Generate key pair for 1024-bit RSA encryption and decryption
Key publicKey = null;
Key privateKey = null;
try {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024);
KeyPair kp = kpg.genKeyPair();
publicKey = kp.getPublic();
privateKey = kp.getPrivate();
} catch (Exception e) {
Log.e(TAG, "RSA key pair error");
}
//textPublicKey.setText(String.valueOf(publicKey));
//textPrivateKey.setText(String.valueOf(privateKey));
}
public void savePrivateKey(String[] args) throws FileNotFoundException {
try {
// store private key locally
String string = String.valueOf(privateKey);
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
}
catch (Exception e) {
Log.e(TAG, "Error saving file.");
}
}
public void retrievePrivateKey(String[] args) throws FileNotFoundException {
try {
FileInputStream fis = openFileInput(FILENAME);
StringBuffer fileContent = new StringBuffer("");
byte[] buffer = new byte[1024];
while ((n = fis.read(buffer)) != -1) ;
{
fileContent.append(new String(buffer, 0, n));
}
textPrivateKey.setText(String.valueOf(fileContent));
}
catch(IOException e) {
Log.e(TAG, "Error opening file.");
}
}
public void testData(View view){
AsymmetricAlgorithmRSA();
savePrivateKey();
retrievePrivateKey();
}
Both savePrivateKey and retrievePrivateKey accept a String[], although they do not use them. Just drop these redundant parameter specifications and you should be fine:
public void savePrivateKey() throws FileNotFoundException {
// code here...
}
public void retrievePrivateKey() throws FileNotFoundException {
// code here...
}
savePrivateKey(); --> method which has no arguments. But you have implemented a method with arguments as String[] public void savePrivateKey(String[] args) throws FileNotFoundException.. Pass as String[] as argument or change the method signature.
Related
I am facing some issue in decrypting a pgp encrypted file. I have the pass phase and the file with me. Now to decrypt it I need to use a class PBEFileProcessor (best guess) provided by bouncycastle in their jar. I have included the jar in my eclipse project and have made a new class which calls this class to decrypt the file. But i am having hard time debugging it.
The code for the same is:
import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.security.NoSuchProviderException;import java.security.SecureRandom;import java.security.Security;import org.bouncycastle.bcpg.ArmoredOutputStream;import org.bouncycastle.bcpg.CompressionAlgorithmTags;import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags;import org.bouncycastle.jce.provider.BouncyCastleProvider;import org.bouncycastle.openpgp.PGPCompressedData;import org.bouncycastle.openpgp.PGPEncryptedDataGenerator;import org.bouncycastle.openpgp.PGPEncryptedDataList;import org.bouncycastle.openpgp.PGPException;import org.bouncycastle.openpgp.PGPLiteralData;import org.bouncycastle.openpgp.PGPPBEEncryptedData;import org.bouncycastle.openpgp.PGPUtil;import org.bouncycastle.openpgp.jcajce.JcaPGPObjectFactory;import rg.bouncycastle.openpgp.operator.jcajce.JcaPGPDigestCalculatorProviderBuilder;import org.bouncycastle.openpgp.operator.jcajce.JcePBEDataDecryptorFactoryBuilder;import org.bouncycastle.openpgp.operator.jcajce.JcePBEKeyEncryptionMethodGenerator;import org.bouncycastle.openpgp.operator.jcajce.JcePGPDataEncryptorBuilder;import org.bouncycastle.util.io.Streams;
public class PBEFileProcessor1 {
private static void decryptFile(String inputFileName, char[] passPhrase)
throws IOException, NoSuchProviderException, PGPException
{
InputStream in = new BufferedInputStream(new FileInputStream(inputFileName));
decryptFile(in, passPhrase);
in.close();
}
/*
* decrypt the passed in message stream
*/
private static void decryptFile(
InputStream in,
char[] passPhrase)
throws IOException, NoSuchProviderException, PGPException
{
in = PGPUtil.getDecoderStream(in);
JcaPGPObjectFactory pgpF = new JcaPGPObjectFactory(in);
PGPEncryptedDataList enc;
Object o = pgpF.nextObject();
if (o instanceof PGPEncryptedDataList)
{
enc = (PGPEncryptedDataList)o;
}
else
{
enc = (PGPEncryptedDataList)pgpF.nextObject();
}
PGPPBEEncryptedData pbe = (PGPPBEEncryptedData)enc.get(0);
InputStream clear = pbe.getDataStream(new JcePBEDataDecryptorFactoryBuilder(new JcaPGPDigestCalculatorProviderBuilder().setProvider("BC").build()).setProvider("BC").build(passPhrase));
JcaPGPObjectFactory pgpFact = new JcaPGPObjectFactory(clear);
//
// if we're trying to read a file generated by someone other than us
// the data might not be compressed, so we check the return type from
// the factory and behave accordingly.
//
o = pgpFact.nextObject();
if (o instanceof PGPCompressedData)
{
PGPCompressedData cData = (PGPCompressedData)o;
pgpFact = new JcaPGPObjectFactory(cData.getDataStream());
o = pgpFact.nextObject();
}
PGPLiteralData ld = (PGPLiteralData)o;
InputStream unc = ld.getInputStream();
OutputStream fOut = new BufferedOutputStream(new FileOutputStream(ld.getFileName()));
Streams.pipeAll(unc, fOut);
fOut.close();
if (pbe.isIntegrityProtected())
{
if (!pbe.verify())
{
System.err.println("message failed integrity check");
}
else
{
System.err.println("message integrity check passed");
}
}
else
{
System.err.println("no message integrity check");
}
}
private static void encryptFile(
String outputFileName,
String inputFileName,
char[] passPhrase,
boolean armor,
boolean withIntegrityCheck)
throws IOException, NoSuchProviderException
{
OutputStream out = new BufferedOutputStream(new FileOutputStream(outputFileName));
encryptFile(out, inputFileName, passPhrase, armor, withIntegrityCheck);
out.close();
}
private static void encryptFile(
OutputStream out,
String fileName,
char[] passPhrase,
boolean armor,
boolean withIntegrityCheck)
throws IOException, NoSuchProviderException
{
if (armor)
{
out = new ArmoredOutputStream(out);
}
try
{
byte[] compressedData = BouncyCastlePGPExampleUtil.compressFile(fileName, CompressionAlgorithmTags.ZIP);
PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(new JcePGPDataEncryptorBuilder(SymmetricKeyAlgorithmTags.CAST5)
.setWithIntegrityPacket(withIntegrityCheck).setSecureRandom(new SecureRandom()).setProvider("BC"));
encGen.addMethod(new JcePBEKeyEncryptionMethodGenerator(passPhrase).setProvider("BC"));
OutputStream encOut = encGen.open(out, compressedData.length);
encOut.write(compressedData);
encOut.close();
if (armor)
{
out.close();
}
}
catch (PGPException e)
{
System.err.println(e);
if (e.getUnderlyingException() != null)
{
e.getUnderlyingException().printStackTrace();
}
}
}
public static void main(
String[] args)
throws Exception
{
Security.addProvider(new BouncyCastleProvider());
if (args[0].equals("-e"))
{
if (args[1].equals("-a") || args[1].equals("-ai") || args[1].equals("-ia"))
{
encryptFile(args[2] + ".asc", args[2], args[3].toCharArray(), true, (args[1].indexOf('i') > 0));
}
else if (args[1].equals("-i"))
{
encryptFile(args[2] + ".bpg", args[2], args[3].toCharArray(), false, true);
}
else
{
encryptFile(args[1] + ".bpg", args[1], args[2].toCharArray(), false, false);
}
}
else if (args[0].equals("-d"))
{
decryptFile(args[1], args[2].toCharArray());
}
else
{
System.err.println("usage: PBEFileProcessor -e [-ai]|-d file passPhrase");
}
}
}
The java terminal command is : C:\Users\anirudgu\eclipse-workspace\Decryptfile\bin>java PBEFileProcessor1 -d C:\Users\anirudgu\eclipse-workspace\Decryptfile\bin\PTO_data_26_06_2019_16_04.csv Passphase
But the error I am receiving is
Exception in thread "main" java.lang.ClassCastException: org.bouncycastle.openpgp.PGPPublicKeyEncryptedData cannot be cast to org.bouncycastle.openpgp.PGPPB
EEncryptedData
at PBEFileProcessor1.decryptFile(PBEFileProcessor1.java:90)
at PBEFileProcessor1.decryptFile(PBEFileProcessor1.java:60)
at PBEFileProcessor1.main(PBEFileProcessor1.java:215)
But I am able to encrypt this file with the same code.
The jar file that are used are available here
I'm trying to decrypt with my own key the following string:
"zW4%3D1p1%2AjR9E"
private static void init(String password) throws Exception {
PBEKeySpec PBEKeySpecification = new PBEKeySpec(password.toCharArray());
keyDES = SecretKeyFactory.getInstance(encrypted_algorithm).generateSecret(PBEKeySpecification);
myCipher = Cipher.getInstance(encrypted_algorithm);
algorithmSpecification = new PBEParameterSpec(salt, iterationCounter);
}
public static void main(String[] args) throws Exception {
String input = "zW4%3D1p1%2AjR9E";
String infoDesencriptada = null;
try {
init("abc123ab");
myCipher.init(2, keyDES, algorithmSpecification);
BASE64Decoder base64Enc = new BASE64Decoder();
byte[] arrayBase64Enc = base64Enc.decodeBuffer(input);
byte[] decryptedBytes = myCipher.doFinal(arrayBase64Enc);
infoDesencriptada = new String(decryptedBytes, "UTF8");
} catch (Exception var5) {
System.out.println("Some exception:" + var5.getMessage());
var5.printStackTrace();
}
}
I'm getting this error: javax.crypto.BadPaddingException: Given final block not properly padded
Any help?
In the question text the data is "zW4%3D1p1%2AjR9E" but in the code it is "zW4%3D1p1%2AjR9E7", note the extra trailing 7.
The input must be a multiple of the block size, 8-bytes for DES so it seems there is a simple entry error in the code.
I was trying to make a file File Locker App for Android. For encryption & Decryption I used some code which I previously tested on JAVA. It works fine on JAVA, But Fails to Create The Decrypted File on Android platform.
My Code is something like bellow,
public class Cryptographer {
private static final String ALGORITHM = "AES";
private final static String ALGO_RANDOM_NUM_GENERATOR = "SHA1PRNG";
public static int encrypt(String key, File inputFile, File outputFile)
throws CryptographyException {
if(!outputFile.getParentFile().exists())outputFile.getParentFile().mkdir();
return StartCryptography(Cipher.ENCRYPT_MODE, key, inputFile, outputFile);
}
public static int decrypt(String key, File inputFile, File outputFile)
throws CryptographyException {
if(!outputFile.getParentFile().exists())outputFile.getParentFile().mkdir();
return StartCryptography(Cipher.DECRYPT_MODE, key, inputFile, outputFile);
}
private static int StartCryptography(int cipherMode, String key, File inputFile,
File outputFile) throws CryptographyException {
int performance = -1;
try {
SecureRandom random = SecureRandom.getInstance(ALGO_RANDOM_NUM_GENERATOR);
random.setSeed(key.getBytes());
KeyGenerator generator = KeyGenerator.getInstance(ALGORITHM);
generator.init(random);
SecretKey key1 = generator.generateKey();
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(cipherMode, key1);
FileInputStream inputStream = new FileInputStream(inputFile);
byte[] inputBytes = new byte[(int) inputFile.length()];
inputStream.read(inputBytes);
byte[] outputBytes = cipher.doFinal(inputBytes);
FileOutputStream outputStream = new FileOutputStream(outputFile);
outputStream.write(outputBytes);
inputStream.close();
outputStream.close();
performance = 1;
} catch (NoSuchPaddingException | NoSuchAlgorithmException
| InvalidKeyException | BadPaddingException
| IllegalBlockSizeException | IOException ex) {
throw new CryptographyException("Error encrypting/decrypting file", ex);
} finally {
return performance;
}
}
}
I am using a button which when pressed All Files From a declared Array Should First be encrypted, and then the encrypted file will be decrypted to another location. But no Decrypted file is created.
My onClick Method of the button looks like bellow,
public void onKeyDown1(View view) throws CryptographyException {
File outfile = new File(ExternalStorageDirectoryPath, "Encrypted");
File outfileDec = new File(ExternalStorageDirectoryPath, "Decrypted");
for (MyFiles f : files) {
if (f.getCheckstate()) {
File EncFile=new File(outfile,f.getName());
//File DecFile=new File(outfileDec,f.getName());
Cryptographer.encrypt(key, f, EncFile);
Cryptographer.decrypt(key, EncFile, DecFile);
}
}
}
Someone please help me..!!
The ExternalStorageDirectoryPathis a String retrieved by Calling Environment.getExternalStorageDirectory().getAbsolutePath(); .
And MyFiles Class is
public class MyFiles extends File {
boolean Checkstate=false;
public MyFiles(File dir, String name) {
super(dir, name);
}
public MyFiles(String path) {
super(path);
}
public MyFiles(String dirPath, String name) {
super(dirPath, name);
}
public MyFiles(URI uri) {
super(uri);
}
public void setCheckstate(boolean checkstate) {
Checkstate = checkstate;
}
public boolean getCheckstate(){
return Checkstate;
}
public MyFiles[] listFiles(FileFilter filter) {
MyFiles[] files = listFiles();
if (filter == null || files == null) {
return files;
}
List<MyFiles> result = new ArrayList<MyFiles>(files.length);
for (MyFiles file : files) {
if (filter.accept(file)) {
result.add(file);
}
}
return result.toArray(new MyFiles[result.size()]);
}
public MyFiles[] listFiles() {
return filenamesToFiles(list());
}
private MyFiles[] filenamesToFiles(String[] filenames) {
if (filenames == null) {
return null;
}
int count = filenames.length;
MyFiles[] result = new MyFiles[count];
for (int i = 0; i < count; ++i) {
result[i] = new MyFiles(this, filenames[i]);
}
return result;
}
}
I suppose it might be lack of permissions in Manifest file of your android app. Check: http://developer.android.com/guide/topics/manifest/manifest-intro.html
Or you are trying to write in a location your app is not allowed
I want to hash a file in Java by calling a file that ends with .raw. These are the codes I used:
FileSearch.java
public class FileSearch
{
private static final File file = null;
public static File findfile(File file) throws IOException
{
String drive = (new DetectDrive()).USBDetect();
Path start = FileSystems.getDefault().getPath(drive);
Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
{
if (file.toString().endsWith(".raw"))
{
System.out.println(file);
}
return FileVisitResult.CONTINUE;
}
});
return file;
}
public static void main(String[] args) throws Exception
{
Hash hasher = new Hash();
FileSearch.findfile(file);
try
{
if (file.toString().endsWith("raw"))
{
hasher.hash(file);
}
} catch (IOException e)
{
e.printStackTrace();
}
}
}
Hash.java
public class Hash
{
public void hash(File file) throws Exception
{
MessageDigest md = MessageDigest.getInstance("MD5");
FileInputStream fis = new FileInputStream(file);
byte[] dataBytes = new byte[1024];
int nread = 0;
while ((nread = fis.read(dataBytes)) != -1)
{
md.update(dataBytes, 0, nread);
};
byte[] mdbytes = md.digest();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < mdbytes.length; i++)
{
sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
}
System.out.println("Digest(in hex format):: " + sb.toString());
}
}
The first code is used to find the file and perform hash by running the main method and the second code is the method for hashing the file (by MD5). However, when I run the it gives an ouput:
"name of raw file"
Exception in thread "main" java.lang.NullPointerException at FileSearch.main(FileSearch.java:33)
line 33 is the if (file.toString().endsWith("raw")) portion. Anyone knows how I can fix this?
You never initalize file with anything (Well, you initalize it with null)
private static final File file = null;
So when you call
if (file.toString().endsWith("raw"))
file can only be null.
What you probably want is just
file = FileSearch.findfile(file);
See:
What is a NullPointerException, and how do I fix it?
I have problem with DSA signature. My DSA code:
public byte[] signing(String text, PrivateKey privatekey) throws Exception {
byte[] textByte = text.getBytes();
Signature sign = Signature.getInstance("DSA");
sign.initSign(privatekey);
sign.update(textByte);
return sign.sign();
}
public boolean verify(String text, byte[] signature, PublicKey publickey) throws Exception {
byte[] textByte = text.getBytes();
Signature sign = Signature.getInstance("DSA");
sign.initVerify(publickey);
sign.update(textByte);
return sign.verify(signature);
}
And I run it on button action:
private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {
String message = jTextArea1.getText();
try {
signed = dsa.signing(message, privKey);
} catch (Exception ex) {
Logger.getLogger(DSAFrame.class.getName()).log(Level.SEVERE, null, ex);
}
String signedString = new String(signed);
jTextArea2.setText(signedString);
}
private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {
String signedString = jTextArea1.getText();
signToVer = jTextArea2.getText().getBytes();
try {
boolean correct = dsa.verify(signedString, signToVer, pubKey);
if(correct == true) {
JOptionPane.showMessageDialog(this, "Podpis poprawny", "Sukces", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(this, "Podpis niepoprawny", "Błąd", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception ex) {
Logger.getLogger(DSAFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
When I want verify signature, it throw me an java.security.SignatureException: invalid encoding for signature. I think, it's a problem with conversion string to byte array and back. But I don't know how to make it work.