Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Encrypt String using x509Certificate private Key wih RSA
#1
Hi friends,
Kindly help on the above topic.
I have a .cer file which I want to use to encrypt a password with. I have a java equivalent code but want to do it in vb.net

Code:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.safaricom.security;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

import javax.crypto.Cipher;

/**
*
* @author smutungi
*/
public class TheCipher {

    public static final String ALGORITHM = "RSA";
    public static final String PRIVATE_KEY_FILE = "D:/vas\\Mwamba\\B2C_Rollout\\ApiMessageEncryptionKey.key";
    public static final String PUBLIC_KEY_FILE = "D:/Documents/Projects/G2/cert/saf.cer";

    public static void generateKey() {
        try {
            final KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
            keyGen.initialize(1024);
            final KeyPair key = keyGen.generateKeyPair();

            File privateKeyFile = new File(PRIVATE_KEY_FILE);
            File publicKeyFile = new File(PUBLIC_KEY_FILE);

            // Create files to store public and private key
            if (privateKeyFile.getParentFile() != null) {
                privateKeyFile.getParentFile().mkdirs();
            }
            privateKeyFile.createNewFile();

            if (publicKeyFile.getParentFile() != null) {
                publicKeyFile.getParentFile().mkdirs();
            }
            publicKeyFile.createNewFile();

            // Saving the Public key in a file
            ObjectOutputStream publicKeyOS = new ObjectOutputStream(
                    new FileOutputStream(publicKeyFile));
            publicKeyOS.writeObject(key.getPublic());
            publicKeyOS.close();

            // Saving the Private key in a file
            ObjectOutputStream privateKeyOS = new ObjectOutputStream(
                    new FileOutputStream(privateKeyFile));
            privateKeyOS.writeObject(key.getPrivate());
            privateKeyOS.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static boolean areKeysPresent() {

        File privateKey = new File(PRIVATE_KEY_FILE);
        File publicKey = new File(PUBLIC_KEY_FILE);

        if (privateKey.exists() && publicKey.exists()) {
            return true;
        }
        return false;
    }

    public static byte[] encrypt(String text, PublicKey key) {
        byte[] cipherText = null;
        try {
            // get an RSA cipher object and print the provider
            final Cipher cipher = Cipher.getInstance(ALGORITHM);
            // encrypt the plain text using the public key
            cipher.init(Cipher.ENCRYPT_MODE, key);
            cipherText = cipher.doFinal(text.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cipherText;
    }

    public static String decrypt(byte[] text, PrivateKey key) {
        byte[] dectyptedText = null;
        try {
            // get an RSA cipher object and print the provider
            final Cipher cipher = Cipher.getInstance(ALGORITHM);

            // decrypt the text using the private key
            cipher.init(Cipher.DECRYPT_MODE, key);
            dectyptedText = cipher.doFinal(text);

        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return new String(dectyptedText);
    }

    public static void main(String[] args) {
        String message = "";
        byte[] messageBytes;
        byte [] tempPub = null;
        String sPub = null;
        byte[] ciphertextBytes = null;
        byte[] textBytes = null;
        try {

            // Check if the pair of keys are present else generate those.
            if (!areKeysPresent()) {
                // Method generates a pair of keys using the RSA algorithm and stores it
                // in their respective files
                generateKey();
            }

            final String originalText = "SOFTUNI_INIT";
            ObjectInputStream inputStream = null;
            final PublicKey publicKey = null;

            InputStream inStream = new FileInputStream("D:\\vas\\Mwamba\\Safaricom Broker\\20130924\\saf.cer");
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            X509Certificate cert =(X509Certificate)cf.generateCertificate(inStream);
            inStream.close();

            // Read the public key from certificate file
            PublicKey pubkey = (PublicKey) cert.getPublicKey();

            final byte[] cipherText = encrypt(originalText, pubkey);
            tempPub = pubkey.getEncoded();
            sPub = new String( tempPub );
            System.out.println("CipherText = " + new String(Base64.encode(cipherText))+  "\n" );
            System.out.println("Issued by = " + cert.getIssuerDN() + "\n" );
            System.out.println("Public key from certificate file:\n" + sPub.toString() + "\n");
            System.out.println("Public Key Algorithm = " + cert.getPublicKey().getAlgorithm() + "\n" );

//            InputStream inStream_ = new FileInputStream("D:\\vas\\privateBrokerKey.key");
//            CertificateFactory cf_ = CertificateFactory.getInstance("X.509");
//            X509Certificate cert_ =(X509Certificate)cf_.generateCertificate(inStream_);
//            inStream.close();
//
//            PrivateKey privateKey;
//            privateKey = (PrivateKey) inStream_.readObject();
//            final String plainText = decrypt(cipherText, privateKey);
//            System.out.println("Plaintext = " + plainText + "\n" );

//            inputStream = new ObjectInputStream(new FileInputStream(PUBLIC_KEY_FILE));
//      publicKey. = (PublicKey) inputStream.readObject();
//      final byte[] cipherText = encrypt(originalText, publicKey);

//            inputStream =  new ObjectInputStream(new FileInputStream(PUBLIC_KEY_FILE));
//            CertificateFactory f = CertificateFactory.getInstance("X.509");
//X509Certificate certificate = (X509Certificate)f.generateCertificate(inputStream);
//PublicKey pk = certificate.getPublicKey();
      //final PublicKey publicKey = (PublicKey) inputStream.readObject();
      //final byte[] cipherText = encrypt(originalText, pk);

            // Encrypt the string using the public key
           // FileInputStream fin = new FileInputStream(PUBLIC_KEY_FILE);



            // Decrypt the cipher text using the private key.
            //inputStream = new ObjectInputStream(new FileInputStream(PRIVATE_KEY_FILE));
           // final PrivateKey privateKey = (PrivateKey) inputStream.readObject();
            //final String plainText = decrypt(cipherText, privateKey);

            // Printing the Original, Encrypted and Decrypted Text
//            System.out.println("Original Text: " + originalText);
//            System.out.println("Encrypted Text: " + new String(cipherText));
            //System.out.println("Decrypted Text: " + plainText);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String hex(String sPub) {
        sPub.toString();
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
}
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [C#] BitCrypt - Visually Encrypt Binary Data (Bitmap Structures) AceInfinity 4 1,993 08-01-2012, 05:14 PM
Last Post: AceInfinity
  Combination Cracker - String Variant Builder - Developed by AceInfinity AceInfinity 0 1,347 03-15-2012, 06:05 PM
Last Post: AceInfinity
  String MD5 Hasher (Coded by Ace) AceInfinity 20 7,322 10-10-2011, 11:57 AM
Last Post: Greyersting
  [TuT] Trigger a Button With a Key Black Ghost 12 6,367 08-01-2011, 11:11 PM
Last Post: Jacko
  [request] how to encrypt server / client packets {C#,C++,VB.NET or Delphi} KoBE 2 2,519 07-02-2011, 08:11 AM
Last Post: besimbicer

Forum Jump:


Users browsing this thread: 1 Guest(s)