function StringEncrypter( encryptionScheme:String, encryptionKey:String ){ try{ encryptionScheme = encryptionScheme || this.DESEDE_ENCRYPTION_SCHEME; encryptionKey = encryptionKey || this.DEFAULT_ENCRYPTION_KEY; if( encryptionKey.length < 24 ){ throw new java.lang.Exception( 'Encryption key was less than 24 characters.' ); } var keyAsBytes = encryptionKey.getBytes( this.UNICODE_FORMAT ); switch( encryptionScheme ){ case this.DESEDE_ENCRYPTION_SCHEME: this.keySpec = new javax.crypto.spec.DESedeKeySpec( keyAsBytes ); break; case this.DES_ENCRYPTION_SCHEME: this.keySpec = new javax.crypto.spec.DESKeySpec( keyAsBytes ); break; default: throw new java.lang.Exception( "Encryption scheme not supported: " + encryptionScheme ); } this.keyFactory = javax.crypto.SecretKeyFactory.getInstance( encryptionScheme ); this.cipher = javax.crypto.Cipher.getInstance( encryptionScheme ); } catch( e ){ /* your exception handling */ } } StringEncrypter.prototype = { DESEDE_ENCRYPTION_SCHEME: "DESede", DES_ENCRYPTION_SCHEME: "DES", DEFAULT_ENCRYPTION_KEY: "The ships hung in the sky in much the same way that bricks don't.", UNICODE_FORMAT: "UTF8", keySpec: null, keyFactory: null, cipher: null, encrypt: function( unencryptedString ){ if( !unencryptedString ){ return ''; } try { var key = this.keyFactory.generateSecret( this.keySpec ); this.cipher.init( javax.crypto.Cipher.ENCRYPT_MODE, key ); var clearText = unencryptedString.getBytes( this.UNICODE_FORMAT ); var cipherText = this.cipher.doFinal( clearText ); var base64encoder = new sun.misc.BASE64Encoder(); return base64encoder.encode( cipherText ); } catch( e ){ /* your exception handling */ } }, decrypt: function( encryptedString ){ if( !encryptedString ){ return ''; } try { var key = this.keyFactory.generateSecret( this.keySpec ); this.cipher.init( javax.crypto.Cipher.DECRYPT_MODE, key ); var base64decoder = new sun.misc.BASE64Decoder(); var clearText = base64decoder.decodeBuffer( encryptedString ); var cipherText = this.cipher.doFinal( clearText ); return new java.lang.String( cipherText ); } catch( e ){ /* your exception handling */ } } }
var encrypter = new StringEncrypter(); encrypter.encrypt( unencryptedString ); var encrypter = new StringEncrypter(); encrypter.decrypt( encryptedString );