欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

密码学中的DES简化版

程序员文章站 2022-06-15 11:20:33
...
package com.hengyunsoft.cryptography.sign.desimpl;

import java.util.Arrays;
import java.util.Random;

import com.hengyunsoft.cryptography.sign.SignReversible;

public class SimpleDesSign implements SignReversible {

//下面这个是秘钥
private byte[] secretKeys = new byte[] {5,62,54,110,26,57,96,41,96,45,12,74,9,63,7,4,120,44}; //56 bit 秘钥
public SimpleDesSign() {
// Random r = new Random();
// r.nextBytes(secretKeys);
}
@Override
public byte[] encrypt(byte[] b) {
if(b.length !=密码学中的DES简化版
            
    
    博客分类: 密码学 密码学des组合密码位移变换  {
throw new IllegalArgumentException();
}
Entity[] fs = new Entity[17];
fs[0] = IP(b);
for (int i = 1; i <= 16; i++) {
fs[i] = new Entity();
fs[i].l = fs[i-1].r;
fs[i].r = xor(fs[i-1].l , f(fs[i-1].r,i));
}
return DIP(fs[16]);
}


/**
* 组合
* @param entity
* @return
*/
private byte[] DIP(Entity entity) {
byte[] result = new byte[8];
byte[] l = entity.l;
for (int i = 0; i < 4; i++) {
result[i] = l[i];
}
l = entity.r;
for (int i = 4; i < 8; i++) {
result[i] = l[i-4];
}
return result;
}

private byte[] xor(byte[] l, byte[] f) {
byte[] result = new byte[l.length];
for (int i = 0; i < l.length; i++) {
result[i] = (byte) (l[i] ^ f[i]);
}
return result;
}

private byte[] f(byte[] r, int secretKeyBitIndex) {
secretKeyBitIndex = secretKeyBitIndex*2;
int index = secretKeyBitIndex >> 3;
int startIndex = secretKeyBitIndex & 7;
byte[] secretKey  = new byte[4];
if(startIndex == 0) {
for (int i = index,j=0; j < secretKey.length; i++,j++) {
secretKey[j] = secretKeys[i];
}
} else {
for (int i = index,j=0; j < secretKey.length; i++,j++) {
secretKey[j] = (byte) ((byte)(secretKeys[i] >> startIndex) | (byte)(secretKeys[i+1] << (8-startIndex))) ;
}
}
byte[] result = new byte[4];
for (int i = 0; i < result.length; i++) {
result[i] = (byte) (r[i] ^ secretKey[i]);
}
return result;
}

private byte[] Df(byte[] r, int i) {

return f(r, i);
}

/**
* 密码分组
* @param b
* @return
*/
private Entity IP(byte[] b) {

Entity result = new Entity();
result.l = Arrays.copyOfRange(b, 0, 4);
result.r = Arrays.copyOfRange(b, 4,密码学中的DES简化版
            
    
    博客分类: 密码学 密码学des组合密码位移变换 ;
return result;
}

@Override
public byte[] decrypt(byte[] b) {
if(b.length !=密码学中的DES简化版
            
    
    博客分类: 密码学 密码学des组合密码位移变换  {
throw new IllegalArgumentException();
}
Entity[] fs = new Entity[17];
fs[16] = IP(b);
for (int i = 16; i >= 1; i--) {
fs[i-1] = new Entity();
fs[i-1].r = fs[i].l;
fs[i-1].l = xor(fs[i].r , Df(fs[i-1].r,i));
}
return DIP(fs[0]);
}

private static class  Entity{
private byte[] l;
private byte[] r;
}

public static void main(String[] args) {
SimpleDesSign s = new SimpleDesSign();
byte[] encode = s.encrypt("12549632".getBytes());
System.out.println(new String(encode));
System.out.println(new String(s.decrypt(encode)));
}
}