Failed to call DBMS_CRYPTO.ENCRYPT / DECRYPT
I tried to use Oracle 11gR2 DBMS_CRYPTO to perform AES256 encryption/decryption. From the Oracle Ref., it specifies "Security Model - Oracle Database installs this package in the SYS schema. You can then grant package access to existing users and roles as needed." So requested DBA to grant EXECUTE privilege for the SYS.DBMS_CRYPTO.
I successfully run the SQL "select DBMS_CRYPTO.RANDOMBYTES(64) from dual;", but when I tried to implement Package body. The compiler prompted errors: PLS-00201: identified 'DBMS_CRYPTO' must be declared.
Please kindly help and advise. Thanks!
Src code of the package body:
CREATE OR REPLACE PACKAGE BODY PKG_TOOLKIT AS
g_encryption_type PLS_INTEGER := DBMS_CRYPTO.ENCRYPT_AES256 + DBMS_CRYPTO.CHAIN_CBC + DBMS_CRYPTO.PAD_PKCS5;
FUNCTION encrypt (p_text IN VARCHAR2) RETURN RAW IS
l_key VARCHAR2(512);
l_text VARCHAR2(32767) := p_text;
l_encrypted RAW(32767);
BEGIN
getKey(l_key);
l_encrypted := DBMS_CRYPTO.ENCRYPT(src => UTL_I18N.STRING_TO_RAW(l_text, 'AL32UTF8'),
typ => g_encryption_type,
key => UTL_I18N.STRING_TO_RAW(l_key, 'AL32UTF8'));
RETURN l_encrypted;
END;
FUNCTION decrypt (p_raw IN RAW) RETURN VARCHAR2 IS
l_key VARCHAR2(512);
l_decrypted VARCHAR2(32767);
BEGIN
getKey(l_key);
l_decrypted := DBMS_CRYPTO.DECRYPT(src => p_raw,
typ => g_encryption_type,
key => UTL_I18N.STRING_TO_RAW(l_key, 'AL32UTF8'));
RETURN RTrim(UTL_I18N.RAW_TO_CHAR(l_decrypted, 'AL32UTF8'));
END;
END PKG_TOOLKIT;
/
From the Package DBMS_CRYPTO -> Grants, I found there is a privilege "EXECUTE" granted to grantee "ORADEV1". "ORADEV1" is the login ID I'm using to connect to Oracle. Can I tell whether the DBA is granting the privilege to this id or it's role thru Oracle Developer?
Similar Messages
-
Encryption/Decryption failure for pdf and MSWord files
Hi,
Is there anybody to help me to find out what is wrong with my class (listing below)? I am sucessfuly using this class to encrypt and decrypt txt, html files but for unknown reasons I am unable to use it for e.g. pdf files. The encrypion somehow works but any atempt to decrypt is a failure.
/* This class accepts an input file, encrypts/decrypts it using DES algorithm and
writes the encrypted/decrypted output to an output file. DES is used in Cipher
Block Chaining mode with PKCS5Padding padding scheme. Note that DES is a symmetric
block cipher that uses 64-bit keys for encryption. A password of length no less
than 8 is to be passed to the encryptFile/ decryptFile methods. This password is
used to generate the encryption key. All exception handling is to be done by
calling methods. These exceptions are thrown by encryptFile/ decryptFile methods.
The input buffer is 64 bytes, 8 times the key size.
import java.io.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.*;
import java.security.spec.*;
public class Crypto
public Crypto(FileInputStream inStream_, FileOutputStream outStream_)
fInputStream_ = inStream_;
fOutputStream_ = outStream_;
public void encryptFile(String password_) throws InvalidKeySpecException, InvalidKeyException,
InvalidAlgorithmParameterException, IllegalStateException, IOException, Exception
DataOutputStream dataOutStream_ = new DataOutputStream(fOutputStream_);
// key generation
SecretKey encryptKey_ = createEncryptionKey(password_);
// Cipher initialization
Cipher cipher_= Cipher.getInstance(cipherType);
cipher_.init(Cipher.ENCRYPT_MODE, encryptKey_);
// write initialization vector to output
byte[] initializationVector_ = cipher_.getIV();
dataOutStream_.writeInt(initializationVector_.length);
dataOutStream_.write(initializationVector_);
// start reading from input and writing encrypted data to output
while (true) {
inputLength_ = fInputStream_.read(input_);
if (inputLength_ ==-1) break;
byte[] output_ = cipher_.update(input_, inputOffset_, inputLength_);
if (output_ != null)
dataOutStream_.write(output_);
// finalize encryption and wrap up
byte[] output_ = cipher_.doFinal();
if (output_ != null)
dataOutStream_.write(output_);
fInputStream_.close();
dataOutStream_.flush();
dataOutStream_.close();
public void decryptFile(String password_) throws IllegalStateException, IOException, Exception
DataInputStream dataInStream_ = new DataInputStream(fInputStream_);
// key generation
SecretKey encryptKey_ = createEncryptionKey(password_);
// read initialization vector from input
int ivSize_ = dataInStream_.readInt();
byte[] initializationVector_ = new byte[ivSize_];
dataInStream_.readFully(initializationVector_);
IvParameterSpec ivParamSpec_= new IvParameterSpec(initializationVector_);
// Cipher initialization
Cipher cipher_= Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher_.init(Cipher.DECRYPT_MODE, encryptKey_, ivParamSpec_);
// start reading from input and writing decrypted data to output
while (true) {
inputLength_ = fInputStream_.read(input_);
if (inputLength_ ==-1) break;
byte[] output_ = cipher_.update(input_, inputOffset_, inputLength_);
if (output_ != null)
fOutputStream_.write(output_);
// finalize decryption and wrap up
byte[] output_ = cipher_.doFinal();
if (output_ != null)
fOutputStream_.write(output_);
fInputStream_.close();
fOutputStream_.flush();
fOutputStream_.close();
// the following method creates the encryption key using the supplied password
private SecretKey createEncryptionKey(String passwd_) throws InvalidKeySpecException,
InvalidKeyException, NoSuchAlgorithmException
byte[] encryptionKeyData_ = passwd_.getBytes();
DESKeySpec encryptionKeySpec_ = new DESKeySpec(encryptionKeyData_);
SecretKeyFactory keyFactory_ = SecretKeyFactory.getInstance(algorithm_);
SecretKey encryptionKey_ = keyFactory_.generateSecret(encryptionKeySpec_);
return encryptionKey_;
private FileInputStream fInputStream_;
private FileOutputStream fOutputStream_;
private final String algorithm_= "DES";
private final String cipherType= "DES/CBC/PKCS5Padding";
private byte[] input_ = new byte[64]; // The input buffer size is 64
private int inputLength_;
private final int inputOffset_= 0;
}Please can u give me refined code for me///
at [email protected]
Hi,
I found at least one thing wrong. In the decrypt
method you are reading from 'fInputStream_' rather
than 'dataInStream'.
Worked for me on MSWord after changing this!
Roger
// start reading from input and writing decrypted
ted data to output
while (true) {
inputLength_ = fInputStream_.read(input_);
if (inputLength_ ==-1) break;
byte[] output_ = cipher_.update(input_,
input_, inputOffset_, inputLength_);
if (output_ != null)
fOutputStream_.write(output_); -
Encrypt/decrypt using update
Hi,
can someone give me an encrypt/decrypt pair of code samples that use the cipher.update() call.
i am trying it like that but apparently it doesn't work
byte[] temp = new byte[message.length/2];
byte[] temp2 = new byte[message.length/2];
System.arraycopy(message, 0, temp, 0, temp.length);
System.arraycopy(message, temp.length, temp2, 0, temp.length);
ciphertext = new byte[message.length];
System.arraycopy(symmetricCipher.update(temp), 0, ciphertext, 0, temp.length);
System.arraycopy(symmetricCipher.doFinal(temp2), 0, ciphertext, temp.length, temp.length);ode]
>
I don't see how using the inputstream i would avoid
the memory error, when passing anything over
10,000,000. Unless you mean I split the input, and
write small chunks into disk as I encrypt them?Your basic problem is that you have the data as one large array. I don't know how and why you created this large array; I would not to create it unless there was no other way.
Since it does not make sense to create one large encrypted byte array and given that you have a byte array then you can use either
1) Create a ByteArrayInputStream and wrap it in a CipherinputStream. This would allow you to encrypt the array in a sequential manner a few KBytes at a time.
or
2) Encrypt the array a few KBytes at a time using a simple update(array, start, length) that returns the encrypted bytes.
But first, I would try to avoid creating the large 'cleartext' array. -
How to encrypt/decrypt the password
Hi
In our website(JSP,servlet) is running over the Sun One Application server.In website, Contact us information is call by a servlet.when we submit the information and it will connect to the DB. I need to use encrypt/decrypt the password. DB connection information is store in server.xml.
So how to proceed to encrypt/decrypt the password?
please advice/suggestion for the same.
thanks
lalit
Edited by: Lalit107 on Aug 6, 2009 4:49 AMI don't understand what you are saying. Is your password sumitted from the JSP?
-
How to Encrypt - Decrypt the Passwords
Hi,
i am developing an integration between SAP and SFTP.
i want to save the encrypted password of SFTP to database tables and then i want to use the decrypted password to connect SFTP.
how to convert the encrypted password to decrypted?
can somebody help me please?
Best regards.Hi
you will have to encrypt the entered password first and compare the encrypted passwords.
Im not sure, but maybe FM VRM_COMPUTE_MD5 will do the encrypting-job.
just check it out and also check below FM
Try the DB_CRYPTO_PASSWORD function module, there's no way to decrypt it back that I know of. You just pass the user input to the function module and compare the encrypted output to the value stored in the database.
and also try this two
Use the following FM to encrypt
CALL FUNCTION 'FIEB_PASSWORD_ENCRYPT'
Use the following FM to decrypt
CALL FUNCTION 'FIEB_PASSWORD_DECRYPT'
By these FM you can encrypt & decrypt any fields of the Program.
Warm Regards
NZAB -
DBMS_Crypto.Encrypt
Reference to the site:
http://www.oracle.com/technology/oramag/oracle/05-jan/o15security.html
I have created get_enc_val function in the database.
function get_enc_val
p_in in varchar2,
p_key in raw
return raw is
l_enc_val raw (2000);
l_mod number := dbms_crypto.ENCRYPT_AES128
+ dbms_crypto.CHAIN_CBC
+ dbms_crypto.PAD_PKCS5;
begin
l_enc_val := dbms_crypto.encrypt
UTL_I18N.STRING_TO_RAW
(p_in, 'AL32UTF8'),
l_mod,
p_key
return l_enc_val;
end;
When i run the following:
create table test(res_id varchar2(19), res_salary raw(2000));
insert into test
(res_id, res_salary)
values
('001',
get_enc_val (
'2000', dbms_crypto.randombytes (128))
System shows error:
ORA-28239: no key provided
ORA-06512: at "SYS.DBMS_CRYPTO_FFI", line 3
ORA-06512: at "SYS.DBMS_CRYPTO", line 10
ORA-06512: at "BMS.GET_ENC_VAL", line 12
Can anybody help? Thanks a lot!DECLARE
input_string VARCHAR2(16) := 'tigertigertigert';
raw_input RAW(128) :=
UTL_RAW.CAST_TO_RAW(CONVERT(input_string,'AL32UTF8','US7ASCII'));
key_string VARCHAR2(8) := 'scottsco';
raw_key RAW(128) :=
UTL_RAW.CAST_TO_RAW(CONVERT(key_string,'AL32UTF8','US7ASCII'));
encrypted_raw RAW(2048);
encrypted_string VARCHAR2(2048);
decrypted_raw RAW(2048);
decrypted_string VARCHAR2(2048);
-- 1. Begin testing Encryption BEGIN
dbms_output.put_line('> Input String : ' ||
CONVERT(UTL_RAW.CAST_TO_VARCHAR2(raw_input),'US7ASCII','AL32UTF8'));
dbms_output.put_line('> ========= BEGIN TEST Encrypt =========');
encrypted_raw := dbms_crypto.Encrypt(
src => raw_input,
typ => DBMS_CRYPTO.DES_CBC_PKCS5,
key => raw_key);
dbms_output.put_line('> Encrypted hex value : ' ||
rawtohex(UTL_RAW.CAST_TO_RAW(encrypted_raw)));
decrypted_raw := dbms_crypto.Decrypt(
src => encrypted_raw,
typ => DBMS_CRYPTO.DES_CBC_PKCS5,
key => raw_key);
decrypted_string :=
CONVERT(UTL_RAW.CAST_TO_VARCHAR2(decrypted_raw),'US7ASCII','AL32UTF8');
dbms_output.put_line('> Decrypted string output : ' ||
decrypted_string);
if input_string = decrypted_string THEN
dbms_output.put_line('> String DES Encyption and Decryption successful');
END if; dbms_output.put_line(''); dbms_output.put_line('> ========= BEGIN TEST Hash =========');
encrypted_raw := dbms_crypto.Hash(
src => raw_input,
typ => DBMS_CRYPTO.HASH_SH1);
dbms_output.put_line('> Hash value of input string : ' ||
rawtohex(UTL_RAW.CAST_TO_RAW(encrypted_raw)));
dbms_output.put_line('> ========= BEGIN TEST Mac =========');
encrypted_raw := dbms_crypto.Mac(
src => raw_input,
typ => DBMS_CRYPTO.HMAC_MD5,
key => raw_key);
dbms_output.put_line('> Message Authentication Code : ' ||
rawtohex(UTL_RAW.CAST_TO_RAW(encrypted_raw)));
dbms_output.put_line(''); dbms_output.put_line('> End of DBMS_CRYPTO tests '); END; /
error:
dbms_output.put_line('> Input String : ' ||
ERROR at line 17:
ORA-06550: line 17, column 12:
PLS-00103: Encountered the symbol "." when expecting one of the following:
constant exception <an identifier>
<a double-quoted delimited-identifier> table LONG_ double ref
char time timestamp interval date binary national character
nchar
The symbol "<an identifier>" was substituted for "." to continue.
ORA-06550: line 19, column 12:
PLS-00103: Encountered the symbol "." when expecting one of the following:
constant exception <an identifier>
<a double-quoted delimited-identifier> table LONG_ double ref
char time timestamp interval date binary national chara
ORA-06550: line 20, column 15:
PLS-00103: Encountered the symbol "=" when expecting one of the following:
constant exception <an identifier>
<a double-quoted delimited-identifier> table LONG_ double ref
char time timestamp interval date binary national chara
ORA-06550: line 26, column 15:
PLS-00103: Encountered the symbol "." when expecting one of the following:
constant exception <an iden
Please help quickly. -
Dbms_crypto encrypt date number datatype
I am using oracle 11g. I am very new to dbms_crypto. I went through documentation but have following doubts:
Is it mandatory to convert varchar2(32) to RAW to use dbms_crypto.encrypt?
If I change varchar2(32) to RAW, Can I make it RAW(32) or does it needs to be bigger?
Does the RAW size must be in multiple of 16?
How can I encrypt data of datatype date and number using dbms_crypto?
Thanks a lot for your time to clarify my quries?spur230 wrote:
Is it mandatory to convert varchar2(32) to RAW to use dbms_crypto.encrypt?It's not mandatory, but it's certainly a good idea. If you store encrypted data in a VARCHAR2 column, that means that it is subject to character set conversion if it's moved from one database to another or sent from a database to a client machine. But if character set conversion happens, your encrypted data is corrupted.
If I change varchar2(32) to RAW, Can I make it RAW(32) or does it needs to be bigger?
Does the RAW size must be in multiple of 16?It would be helpful to specify exactly what algorithm and parameters you intend to use because it may vary. If, for example, we encrypt using AES-256 with Cipher Block Chaining and PKCS#5 compliant padding (which happens to be the example in the DBMS_CRYPTO manual), the output RAW will always be a multiple of 16 and as large or larger than the input RAW.
A VARCHAR2(32) will either allocate 32 characters of storage or 32 bytes of storage depending on your NLS_LENGTH_SEMANTICS parameter. If you're using the default, it will allocate 32 bytes. But 32 bytes in the database character set may require more than 32 bytes of storage once you convert it to a UTF-8 encoded RAW (which, technically, also isn't required but is a good practice) and, thus, the encrypted string might require more than 32 bytes of storage. Your database character set and the actual data you store/ want to be able to store will influence how likely it is that you'll need a larger RAW than your VARCHAR2.
How can I encrypt data of datatype date and number using dbms_crypto?dbms_crypto only operates on RAW data. Just like you convert strings to RAW before encrypting them, you'd need to convert your dates and numbers to RAW. For numbers, you should be able to use UTL_RAW.CAST_FROM_NUMBER. I don't know of a method of casting dates to a RAW other than converting them to a known string representation and then encrypting that (and, of course, doing the reverse when you decrypt the string and convert it back to a date using that same format).
Justin -
Hi,
I am developing one file-file interface for sending sensitive data from one file system to another file system. As this is sensitive data, i need to decrypt this data ( file i am picking from source system is already encrypted in source directory ) and i need to send it to target system. i found some alternatives like module development and pgp encryption. I am not that much proficient to develop module and i looking at other alternative like pgp. Is PGP is free software?? how can i install and how can i call from my sender adapter?? Please Help.
Thanks
madhusudhan.Hi madhusudan
refer the below link
<u>Encryption & Decryption of data using ABAP</u>
/people/kathirvel.balakrishnan2/blog/2006/11/21/encryption-decryption-of-data-using-abap
<u>JAVA API's for PGP Encryption/Decryption</u>
http://www.bouncycastle.org/documentation.html
you got some examples
Check this document on how to do message level security:
https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/d024ca8e-e76e-2910-c183-8ea4ba681c51
Deploying the SAP Java Cryptographic Toolkit
http://help.sap.com/saphelp_nw04/helpdata/en/8d/cb71b8046e6e469bf3dd283104e65b/frameset.htm
Key Storage Service
http://help.sap.com/saphelp_nw04/helpdata/en/e9/a1dd44d2c83c43afb5ec8a4292f3e0/frameset.htm
If these things are already done then u need juz few modification in the adapter configuration.
In FTP Connection Parameters -> command line -> FTPS (Control and Data connection)
You can also go through the blogs
Encryption(SSL)
/people/varadharajan.krishnasamy/blog/2007/05/11/how-to-use-digital-certificates-for-signing-encrypting-messages-in-xi
https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/docs/library/uuid/b2e7020d-0d01-0010-269c-a98d3fb5d16c
Examples for Using Digital Signatures
http://help.sap.com/saphelp_nw04s/helpdata/en/a4/d0201854fb6a4cb9545892b49d4851/frameset.htm
How to configure Message level security
https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/docs/library/uuid/b2e7020d-0d01-0010-269c-a98d3fb5d16c
document on encryption in adpaters
https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/482aae19-0301-0010-3485-8efd618818d0
Encrypt and Decrypt Data
<b>Pls reward if useful</b> -
How to resolve bug RC4 encrypt-decrypt on iPAD with AIR15 only
Hi everybody,
I have some trouble with AIR15 only, In the past, I created a small game on iPad It could send or receive messge from server. I used lib as3crypto.swc encrypt or decrypt message (RC4). But when I upgrade to AIR15 encrypt-decrypt cannot work ( Another thing about this crash is that it only happens with a release (adhoc or appstore) build but NOT with a debug build). I check so many time but i don't know what is problem here.
Please help me, thanks so much any advice.
P/S: My game have many swf files (code and resource). I must combine multiple SWF files into one.
Class RC4.as
import com.hurlant.crypto.prng.ARC4;
import com.hurlant.util.Base64;
import com.hurlant.util.Hex;
import flash.utils.ByteArray;
public class RC4
private static const key:String = "keytest";
private static var byteKeys:ByteArray = Hex.toArray(Hex.fromString(key));
private static var rc4:ARC4 = new ARC4();
public static function encrypt(clearText:String):String
var byteText:ByteArray = Hex.toArray(Hex.fromString(clearText));
rc4.init(byteKeys);
rc4.encrypt(byteText);
return Base64.encodeByteArray(byteText);
public static function decrypt(encryptedText:String):String
var byteText:ByteArray = Base64.decodeToByteArray(encryptedText);
rc4.init(byteKeys);
rc4.decrypt(byteText);
return Hex.toString(Hex.fromArray(byteText));Sorry, exact message is "this movie could not be played".
There are hundreds of posts about this message but no one states a clear solution to the problem.
Your help will be much appreciated.
Thank you. -
Just rebuilt new HP 355 G2 to Win 7 64 bit. The ONLY driver I can not locate or get to work is the PCI Encryption/Decryption Controller. I installed all latest drivers for this model/OS from both HP and AMD sites still no luck. AMD autodetect utility and Catalyst software installed all other drivers successfully except this one and when completes says all drivers, including chipset, are installed successfully and current.
I am at a complete loss where to get this driver from a OEM site, can you help ?
Device ID's:
PCI\VEN_1022&DEV_1537&SUBSYS_15371022&REV_00
PCI\VEN_1022&DEV_1537&SUBSYS_15371022
PCI\VEN_1022&DEV_1537&CC_108000
PCI\VEN_1022&DEV_1537&CC_1080
Thanks !!!
This question was solved.
View Solution.Hi:
You need to run this driver and then manually install it.
http://h20565.www2.hp.com/hpsc/swd/public/detail?swItemId=vc_133833_1
To manually install the driver go to the device manager and click on the PCI Encryption/Decryption Controller needing the driver.
Click on the driver tab. Click on Update Driver.
Select the Browse my computer for driver software option, and browse to the driver folder that was created when you ran the file.
That folder will be located in C:\SWSetup\sp66974.
Make sure the Include Subfolders box is checked, and the driver should install.
Then reboot. -
Help for a newbie on encryption/decryption
I want to start with a text file.
Read in a line of ascii characters, encrypt it using some algorithm and output it as a new set of ascii characters.
What algorithm should I use?thanks a lot. I got the encryption/decryption working pretty easily.
However, I ran into problem when I got to storing keys:
I stored it fine with this code
try {
KeyGenerator keyGen = KeyGenerator.getInstance("DES");
desKey = keyGen.generateKey();
cipher = Cipher.getInstance("DES");
KeyStore keyStore = KeyStore.getInstance("JKS");
String password = "lemein";
char passwd[] = password.toCharArray();
keyStore.load(null, passwd); //initialize keyStore
Certificate[] chain = new Certificate[1];
String alias = "test";
keyStore.setKeyEntry(alias, desKey, passwd, null);
String fileName = "data/gkey.txt";
FileOutputStream f = new FileOutputStream(fileName);
keyStore.store(f, passwd); // <----------exception happens here
} catch (Exception e)
{ e.printStackTrace();
I got problem when I retrieve it with this code
KeyGenerator kg = null;
Key key = null;
cipher = null;
Security.addProvider(new com.sun.crypto.provider.SunJCE());
byte[] result = null;
try {
KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(new FileInputStream("data/gkey.txt"), "lemein".toCharArray());
key = keyStore.getKey("test", "lemein".toCharArray());
cipher = Cipher.getInstance("DES");
byte[] data = "Hello World!".getBytes();
System.out.println("Original data : " + new String(data));
cipher.init(Cipher.ENCRYPT_MODE, key);
result = cipher.doFinal(data);
System.out.println("Encrypted data: " + new String(result));
} catch (Exception e) {
e.printStackTrace();
I get the error:
java.security.UnrecoverableKeyException: DerInputStream.getLength(): lengthTag=75, too big.
at sun.security.provider.KeyProtector.recover(Unknown Source)
at sun.security.provider.JavaKeyStore.engineGetKey(Unknown Source)
at java.security.KeyStore.getKey(Unknown Source)
Any idea what the problem is?
Thanks -
Why fail to call third party funciton in DLL via JNI but workable in C++?
Hi,
I need someone help me here.
I like to call a function in third party A.dll which is from PowerBuilder App by Java.
So first I worte C++ code to call A.dll for the function to confirm: String feGetMM( String a);
I worte code like here in C++:
typedef char * (CALLBACK PROC_ADDR) ( const char);
const char* NAME = "feGetMM";
PROC_ADDR procAddr;
const char* passin = "123";
char * result;
HINSTANCE hinstLib = LoadLibrary( A.dll ); //load 3rd party library
if(hinstLib!=NULL) {
//get the function address
procAddr = (PROC_ADDR) GetProcAddress(hinstLib,NAME);
if(procAddr!=NULL)
result = (procAddr)( passin ); //call the function
I got right result.<<<<<<<<<<<<<Then second I worte the same as C++ in JNI code to generate B.dll
JNIEXPORT jint JNICALL Java_xxxxx_feGetMM
(JNIEnv *env, jclass cl, jstring jstr) {
typedef char* (CALLBACK PROC_ADDR) ( const char);
const char* NAME = "feGetMM";
PROC_ADDR procAddr;
const char* result;
HINSTANCE hinstLib = LoadLibrary( A.dll ); //load 3rd party library
if(hinstLib!=NULL) {
//get the function address
procAddr = (PROC_ADDR) GetProcAddress(hinstLib,NAME);
const char* cstr = env->GetStringUTFChars(jstr,NULL);
if(procAddr!=NULL)
result = (procAddr)(cstr); //call the function
fails return NULL<<<<<<<<*the B.dll builded successfully, but fail to call for result. The java main() call is fine. The "result" is always NULL.
I worte the same as C++ code in JNI but why it fails in JNI code call by Java?
I will appreciate your help if you could reply it quickly.
Thanks !The crashdump fragment tells me that your program has jumped to location 0. That's usually an uninitialized pointer
-
Encrypt/decrypt AES 256, vorsalt error
Hiyas.
So I'm trying to get encrypt/decrypt to work for AES 256, with both 32byte key and 32byte IVorSalt. (Yup-new java security files v6 installed)
'IF' I 32byte key but dont use a IV at all, I get a nice looking AES 256 result. (I can tell it's AES 256 by looking the length of the encrypted string)
'IF' I use a 32byte key and 16bit salt, I get a AES 128 result (I know- as per docs theyre both s'posed to the same size, but the docs are wrong).
But when i switch to using both a 32byte key AND a 32byte salt I get the error below.
An error occurred while trying to encrypt or decrypt your input string: Bad parameters: invalid IvParameterSpec: com.rsa.jsafe.crypto.JSAFE_IVException: Invalid IV length. Should be 16.
Has anyone 'EVER' gotten encrypt to work for them using AES 256 32byte key and 32byte salt? Is this a bug in CF? Or Java? Or I am doing something wrong?
<!--- ////////////////////////////////////////////////////////////////////////// Here's the Code ///////////////////////////////////////////////////////////////////////// --->
<cfset theAlgorithm = "Rijndael/CBC/PKCS5Padding" />
<cfset gKey = "hzj+1o52d9N04JRsj3vTu09Q8jcX+fNmeyQZSDlZA5w="><!--- these 2 are the same --->
<!---<cfset gKey = ToBase64(BinaryDecode("8738fed68e7677d374e0946c8f7bd3bb4f50f23717f9f3667b2419483959039c", "Hex"))>--->
<cfset theIV = BinaryDecode("7fe8585328e9ac7b7fe8585328e9ac7b7fe8585328e9ac7b7fe8585328e9ac7b","hex")>
<!---<cfset theIV128 = BinaryDecode("7fe8585328e9ac7b7fe8585328e9ac7b","hex")>--->
<cffunction name="DoEncrypt" access="public" returntype="string" hint="Fires when the application is first created.">
<cfargument name="szToEncrypt" type="string" required="true"/>
<cfset secretkey = gKey>
<cfset szReturn=encrypt(szToEncrypt, secretkey, theAlgorithm, "Base64", theIV)>
<cfreturn szReturn>
</cffunction>
<cffunction name="DoDecrypt" access="public" returntype="string" hint="Fires when the application is first created.">
<cfargument name="szToDecrypt" type="string" required="true"/>
<cfset secretkey = gKey>
<cfset szReturn=decrypt(szToDecrypt, secretkey, theAlgorithm, "Base64",theIV)>
<cfreturn szReturn>
</cffunction>
<cfset szStart = form["toencrypt"]>
<cfset szStart = "Test me!">
<cfset szEnc = DoEncrypt(szStart)>
<cfset szDec = DoDecrypt(szEnc)>
<cfoutput>#szEnc# #szDec#</cfoutput>Hi edevmachine,
This Bouncy Castle Encryption CFC supports Rijndael w/ 256-bit block size. (big thanks to Jason here and all who helped w/ that, btw!)
Example:
<cfscript>
BouncyCastleCFC = new path.to.BouncyCastle();
string = "ColdFusion Rocks!";
key = binaryEncode(binaryDecode(generateSecretKey("Rijndael", 256), "base64"), "hex");//the CFC takes hex'd key
ivSalt = binaryEncode(binaryDecode(generateSecretKey("Rijndael", 256), "base64"), "hex");//the CFC takes hex'd ivSalt
encrypted = BouncyCastleCFC.doEncrypt(string, key, ivSalt);
writeOutput(BouncyCastleCFC.doDecrypt(encrypted, key, ivSalt));
</cfscript>
Related links for anyone interested in adding 256-bit block size Rijndael support into ColdFusion:
- An explanation of how to install the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files into ColdFusion
- An explanation of how to install the Bouncy Castle Crypto package into ColdFusion (near bottom, under the "Installing additional security providers" heading)
- An explanation of how to connect the Bouncy Castle classes together
- Bouncy Castle's doc for the Rijndael Engine
And here is the full CFC as posted in the StackOverflow discussion:
<cfcomponent displayname="Bounce Castle Encryption Component" hint="This provides bouncy castle encryption services" output="false">
<cffunction name="createRijndaelBlockCipher" access="private">
<cfargument name="key" type="string" required="true" >
<cfargument name="ivSalt" type="string" required="true" >
<cfargument name="bEncrypt" type="boolean" required="false" default="1">
<cfargument name="blocksize" type="numeric" required="false" default=256>
<cfscript>
// Create a block cipher for Rijndael
var cryptEngine = createObject("java", "org.bouncycastle.crypto.engines.RijndaelEngine").init(arguments.blocksize);
// Create a Block Cipher in CBC mode
var blockCipher = createObject("java", "org.bouncycastle.crypto.modes.CBCBlockCipher").init(cryptEngine);
// Create Padding - Zero Byte Padding is apparently PHP compatible.
var zbPadding = CreateObject('java', 'org.bouncycastle.crypto.paddings.ZeroBytePadding').init();
// Create a JCE Cipher from the Block Cipher
var cipher = createObject("java", "org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher").init(blockCipher,zbPadding);
// Create the key params for the cipher
var binkey = binarydecode(arguments.key,"hex");
var keyParams = createObject("java", "org.bouncycastle.crypto.params.KeyParameter").init(BinKey);
var binIVSalt = Binarydecode(ivSalt,"hex");
var ivParams = createObject("java", "org.bouncycastle.crypto.params.ParametersWithIV").init(keyParams, binIVSalt);
cipher.init(javaCast("boolean",arguments.bEncrypt),ivParams);
return cipher;
</cfscript>
</cffunction>
<cffunction name="doEncrypt" access="public" returntype="string">
<cfargument name="message" type="string" required="true">
<cfargument name="key" type="string" required="true">
<cfargument name="ivSalt" type="string" required="true">
<cfscript>
var cipher = createRijndaelBlockCipher(key=arguments.key,ivSalt=arguments.ivSalt);
var byteMessage = arguments.message.getBytes();
var outArray = getByteArray(cipher.getOutputSize(arrayLen(byteMessage)));
var bufferLength = cipher.processBytes(byteMessage, 0, arrayLen(byteMessage), outArray, 0);
var cipherText = cipher.doFinal(outArray,bufferLength);
return toBase64(outArray);
</cfscript>
</cffunction>
<cffunction name="doDecrypt" access="public" returntype="string">
<cfargument name="message" type="string" required="true">
<cfargument name="key" type="string" required="true">
<cfargument name="ivSalt" type="string" required="true">
<cfscript>
var cipher = createRijndaelBlockCipher(key=arguments.key,ivSalt=arguments.ivSalt,bEncrypt=false);
var byteMessage = toBinary(arguments.message);
var outArray = getByteArray(cipher.getOutputSize(arrayLen(byteMessage)));
var bufferLength = cipher.processBytes(byteMessage, 0, arrayLen(byteMessage), outArray, 0);
var originalText = cipher.doFinal(outArray,bufferLength);
return createObject("java", "java.lang.String").init(outArray);
</cfscript>
</cffunction>
<cfscript>
function getByteArray(someLength)
byteClass = createObject("java", "java.lang.Byte").TYPE;
return createObject("java","java.lang.reflect.Array").newInstance(byteClass, someLength);
</cfscript>
</cfcomponent>
Thanks!,
-Aaron -
Encrypt / Decrypt password
Hi
I'm new in Java and I need to create a function to encrypt / decrypt passwords using the Blowfish algorithm. I know how to create a key, but I don't know how to recover it to decrypt the password.
Another question, Is it possible to use public/private keys in this case???.
Can you give some links or examples please???
Regards
J.C.This is typically done either one of two ways:
1) PBE based encryption. This uses a password or pass phrase to derive
a key to use with a symmetric algorithm.
2) Asymmetric using something like RSA. Typically RSA is used to wrap
the actual symmetric key used to do the encryption but for very short
plaintext it can be used directly on the plaintext. Passwords are a
good example of short plaintext.
Obviously symmetric encryption is a great deal faster than asymmetric
encryption. So if your plaintext was large you would want to use
symmetric. Also Asymmetric encryption is length dependant. AKA if your
public key's modulus is 1024 bits then you could encrypt any plaintext
that was 121 bytes or shorter.
PBE takes a salt (a random byte array) and an iteration count and
hashes a passphrase with the salt iteration number of times to generate
a key that can be reproduced over and over again and used with a
symmetric algorithm. The issue here is that your salt/ic either need
to be hard coded and reused or the values for any single encryption
need to be saved along with the ciphertext. Using the same ic/salt for
a large number of plaintext to ciphertext operations can lead to a
weakening of the pass phrase (aka the key) and aids a cryptoanalyst in
breaking the code. Although it is still difficult it becomes easier
with each successive encryption.
Its upto you which route you take but you should note that private keys
used in asymmetric encryption use PBE to keep them private anyway so in
a sense if you use asymmetric encryption you are really using both
asymmetric encryption and PBE... -
Hello!
I have been trying to use this syntax for encrypting/decrypting BUT I get different values all the time even if I use the same String. I would be really glad if anyone could help me to tell me why. What I want to use this encrypt/decrypt/ is to make some info unreadable in my database but I want to be able to decrypt the info.
-----------------------------syntax----------------------------------------------------------------------
SecretKey key=null;
try{
key = KeyGenerator.getInstance("DES").generateKey();
}catch(Exception e){}
DesEncrypter d= new DesEncrypter(key);
-----------------------------My cryptClass--------------------------------------------------------
public class DesEncrypter {
Cipher ecipher;
Cipher dcipher;
DesEncrypter(SecretKey key) {
try {
ecipher = Cipher.getInstance("DES");
dcipher = Cipher.getInstance("DES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
dcipher.init(Cipher.DECRYPT_MODE, key);
} catch (javax.crypto.NoSuchPaddingException e) {
} catch (java.security.NoSuchAlgorithmException e) {
} catch (java.security.InvalidKeyException e) {
public String encrypt(String str) {
try {
// Encode the string into bytes using utf-8
byte[] utf8 = str.getBytes("UTF8");
// Encrypt
byte[] enc = ecipher.doFinal(utf8);
// Encode bytes to base64 to get a string
return new sun.misc.BASE64Encoder().encode(enc);
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
} catch (java.io.IOException e) {
return null;
public String decrypt(String str) {
try {
// Decode base64 to get bytes
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
// Decrypt
byte[] utf8 = dcipher.doFinal(dec);
// Decode using utf-8
return new String(utf8, "UTF8");
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
} catch (java.io.IOException e) {
return null;
thanks in advance!I don't understand caffeiene's answer but maybe it will help you. It seems to me that you need to encrypt and decrypt the same way across application sessions, etc. Therefore you will need to store your key outside of the application in a file on the server. So you'll have to use a key generator that will let you save the key to a file. That's about all the detail I can give you since I've never worked directly with cryptography. Obviously you'll need to make sure the server is behind a good firewall, or whatever other security measures you deem appropriate to protect the key. It seems unsecure, but you have to persist the key, because otherwise if the app server crashes then the data in the db will be inaccessible.
Maybe you are looking for
-
Hi, How do we set the background color of a column in a report? I have four columns in the table and I want to display the data of each column with different color. Can you help? regards VJ
-
TS3968 logic express 9 wouldn't open for me in snow leopard
logic express 9 wouldn't open for me in snow leopard why is it doing that
-
Best way of approving invoices within the SAP system for payment
Hello Guru, In the past, my client used to send invoices from the unmatched report to the appropriate department head for approval. This approval was recorded in the notes which stayed with the invoice and it would automatically assigned ID and date
-
How to make a code in which i have to detect 3 objects
Hello everyone, I am new in Labview. I want to make a code in which i have to detect 3 objects and they are in different shapes (rectangle, triangle etc). 1. How many objects in image. 2. What is the size of each object in image 3. At what position t
-
Hi All, I want to do some hands on in BPEL correlation. Can anyone suggest me where i can find about the basics of correlation concepts and tutorial on using Correlation in BPEL? Any help appreciated. Thanks & Regards, Ayyadurai