加密字符串时生成数字

时间:2019-04-14 02:32:55

标签: scala encryption

我不是加密专家,但是我需要从输入字符串生成数字并将其转换回原始字符串。

我在互联网上进行了大量搜索,但找不到任何这样做的人。因此,我想从StackOverflow的专家那里寻求帮助。

据我所知,将字符串加密为数字有点棘手,但是我正在从事的项目对此有所要求。

任何执行此操作或使用任何算法的库都可以解决我的问题。

这是我到目前为止的代码

import java.security.MessageDigest
import java.util
import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec
import org.apache.commons.codec.binary.Base64


    object DataMaskUtil {

        def encrypt(key: String, value: String): String = {
          val cipher: Cipher = Cipher.getInstance("AES/ECB/PKCS5Padding")
          cipher.init(Cipher.ENCRYPT_MODE, keyToSpec(key))
           Base64.encodeBase64URLSafeString(cipher.doFinal(value.getBytes("UTF-8")))
        }

        def decrypt(key: String, encryptedValue: String): String = {
          val cipher: Cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING")
          cipher.init(Cipher.DECRYPT_MODE, keyToSpec(key))
          new String(cipher.doFinal(Base64.decodeBase64(encryptedValue)))
        }

        def keyToSpec(key: String): SecretKeySpec = {
          var keyBytes: Array[Byte] = (SALT + key).getBytes("UTF-8")
          val sha: MessageDigest = MessageDigest.getInstance("SHA-1")
          keyBytes = sha.digest(keyBytes)
          keyBytes = util.Arrays.copyOf(keyBytes, 16)
          new SecretKeySpec(keyBytes, "AES")
        }

         private val SALT: String =
        "jMhKlOuJnM34G6NHkqo9V010GhLAqOpF0BePojHgh1HgNg8^72k"

    }

使用Maarten Bodewes提供的想法

object Util2 {

  def encrypt(value: String): BigInteger = {
    val ct = value.getBytes()
    val abyte = 0x4D.toByte
    val byteBuffer = ByteBuffer.allocate(2+ct.length)
    byteBuffer.put(abyte).put(abyte)
    byteBuffer.put(ct)
    val number = new BigInteger(byteBuffer.array())
    number
  }

  def decrypt(ctAsNumber: BigInteger): String = {
    if (ctAsNumber.signum < 0 || ctAsNumber.bitLength < 15) throw new IllegalArgumentException("Magic of ciphertext number doesn't match")
    import java.nio.ByteBuffer
    val fixed = ByteBuffer.allocate((ctAsNumber.bitLength + java.lang.Byte.SIZE - 1) / java.lang.Byte.SIZE)
    fixed.put(ctAsNumber.toByteArray)
    fixed.flip()
    val ct = new Array[Byte](fixed.remaining())
    fixed.get(ct)
    new String(ct)
  }
}

当我测试功能时,输出将在字符串前填充“ MM”

object MainClass {

      def main(args: Array[String]): Unit ={
        val encrypt = Util2.encrypt("Hi")
        println("The encrypted string is :: "+encrypt)

        val decrypt = Util2.decrypt(encrypt)
        println("The decrypted string is :: "+decrypt)

      }

    }

输出

The encrypted string is :: 1296910441
The decrypted string is :: MMHi

1 个答案:

答案 0 :(得分:1)

当然有多种方法可以做到这一点。但是让我们假设我们想要正值(通常是密码学要求的),并且我们希望结果对ECB和CBC有效,但也适用于例如CTR模式加密。在那种情况下,我们还需要确保对前导零进行妥善处理,因为前导零在密文中确实有意义,但对于数字却没有意义。

而且,这是一种在JVM上运行的语言,我们也将使用big endian。

可以通过在左侧添加位/字节值来轻松避免负值和零字节。例如,我们可以使用众所周知的值,这也使您获得了某种最小的保护,以防止密文数字的篡改。然后,您将获得Java语言:

private static BigInteger ciphertextToNumber(byte[] ct) {
    ByteBuffer fixed = ByteBuffer.allocate(2 + ct.length);
    fixed.put((byte) 0x4D).put((byte) 0x42);
    fixed.put(ct);
    BigInteger number = new BigInteger(fixed.array());
    return number;
}

private static byte[] numberToCiphertext(BigInteger ctAsNumber) {
    // if the number is negative then the buffer will be too small
    if (ctAsNumber.signum() < 0 || ctAsNumber.bitLength() < 15) {
        throw new IllegalArgumentException("Magic of ciphertext number doesn't match");
    }
    ByteBuffer fixed = ByteBuffer.allocate((ctAsNumber.bitLength() + Byte.SIZE - 1) / Byte.SIZE);
    fixed.put(ctAsNumber.toByteArray());
    fixed.flip();
    if (fixed.get() != (byte) 0x4D || fixed.get() != (byte) 0x42) {
        throw new IllegalArgumentException("Magic of ciphertext number doesn't match");
    }
    byte[] ct = new byte[fixed.remaining()];
    fixed.get(ct);
    return ct;
}

与密文相比,它的性能相对较高,并且不会增加可能的数字(因为密文可以具有任何字节值,因此当然不可能对其进行压缩)。一种优化方法是直接从BigInteger中提取魔术的字节值,但是对于这种目的,另外一个密文副本可能不会带来多大伤害。

我将它留给您以转换为Scala。


另一个想法是使用RSA RFC中定义的I2OSP或OS2IP,但请注意,RSA填充已经执行了相同的左填充操作,以确保从字节数组到整数的转换得到妥善处理。此外,RSA密文的大小始终与模数相同,而AES加密可能返回不同的大小。

相关问题