Java Encrypt String encrypt(String str)

Here you can find the source of encrypt(String str)

Description

encrypt

License

Open Source License

Declaration

public static byte[] encrypt(String str) throws RuntimeException 

Method Source Code


//package com.java2s;
/*//from  ww w  .  j  a  v a 2  s  . c o m
 * Copyright (c) 2015 Eike Stepper (Berlin, Germany) and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Eike Stepper - initial API and implementation
 */

import java.io.UnsupportedEncodingException;

import java.util.Random;

public class Main {
    public static final String UTF8 = "UTF-8";
    private static final byte[] NO_BYTES = {};
    private static final byte[] KEY = new byte[256];
    private static Random random;

    public static byte[] encrypt(String str) throws RuntimeException {
        if (str == null) {
            return null;
        }

        if (str.length() == 0) {
            return NO_BYTES;
        }

        byte[] bytes = toUTF(str);
        byte[] result = new byte[bytes.length + 1];

        synchronized (KEY) {
            if (random == null) {
                random = new Random(System.currentTimeMillis());
                random.nextBytes(KEY);
            }
        }

        int j = random.nextInt(KEY.length);
        result[bytes.length] = (byte) (j + Byte.MIN_VALUE);
        crypt(bytes, result, bytes.length, j);
        return result;
    }

    public static byte[] toUTF(String str) throws RuntimeException {
        if (str == null) {
            return null;
        }

        if (str.length() == 0) {
            return NO_BYTES;
        }

        try {
            return str.getBytes(UTF8);
        } catch (UnsupportedEncodingException ex) {
            throw new RuntimeException(ex);
        }
    }

    private static void crypt(byte[] bytes, byte[] result, int length, int j) {
        for (int i = 0; i < length; i++) {
            result[i] = (byte) (bytes[i] ^ KEY[j++ % KEY.length]);
        }
    }
}

Related

  1. encrypt(String s)
  2. encrypt(String value)
  3. encryptString(String message)