· 9 years ago · Dec 01, 2016, 01:18 PM
1private static byte[] doThis(String message) {
2 byte[] messageCrypte = null;
3 try {
4 // Certificate Input Stream
5 // LA SSL Certificate to be passed.
6 InputStream inStream = new FileInputStream(certificate);
7
8 // X509Certificate created
9 CertificateFactory cf = CertificateFactory.getInstance("X.509");
10 X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream);
11 inStream.close();
12
13 // Getting Public key using Certficate
14 PublicKey rsaPublicKey = (PublicKey) cert.getPublicKey();
15
16 Cipher encryptCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "SunJCE");
17 encryptCipher.init(Cipher.ENCRYPT_MODE, rsaPublicKey);
18
19 byte[] messageACrypter = message.getBytes();
20 // Encrypted String
21 messageCrypte = encryptCipher.doFinal(messageACrypter);
22 } catch (Exception e) {
23 // TODO: Exception Handling
24 e.printStackTrace();
25 }
26 return messageCrypte;
27}
28
29static byte[] doThis(string message)
30 {
31 X509Certificate cert = new X509Certificate(@"C:Dataabc-rsa-public-key-certificate.cer");
32 byte[] aa = cert.GetPublicKey();
33
34 RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
35 RSAParameters RSAKeyInfo = new RSAParameters();
36 byte[] Exponent = { 1, 0, 1 };
37
38 RSAKeyInfo = RSA.ExportParameters(false);
39 //Set RSAKeyInfo to the public key values.
40 RSAKeyInfo.Modulus = aa;
41 //RSAKeyInfo.Exponent = Exponent;
42 RSA.ImportParameters(RSAKeyInfo);
43 byte[] bb = RSA.Encrypt(GetBytes(message), false);
44 return bb;
45 }
46
47private String getDecryptedString(byte[] credentials, PrivateKey secretKey) throws NoSuchAlgorithmException,
48 NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException,
49 BadPaddingException {
50 String decryptedString;
51 Cipher decryptCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "SunJCE");
52 decryptCipher.init(Cipher.DECRYPT_MODE, secretKey);
53 byte[] messageDecrypte = decryptCipher.doFinal(credentials);
54 decryptedString = new String(messageDecrypte);
55 return decryptedString;
56 }
57
58public static string EncrypIt(string inputString, X509Certificate2 cert)
59{
60 RSACryptoServiceProvider rsaservice = (RSACryptoServiceProvider)cert.PublicKey.Key;
61 byte[] plaintext = Encoding.UTF8.GetBytes(inputString);
62 byte[] ciphertext = rsaservice.Encrypt(plaintext, false);
63 string cipherresult = Convert.ToBase64String(ciphertext);
64 return cipherresult;
65}