本文共 4010 字,大约阅读时间需要 13 分钟。
置换密码算法的原理是不改变明文字符,只将字符在明文中的排列顺序改变,从而实现明文信息的加密。置换密码有时又称为换位密码。 矩阵换位法是实现置换密码的一种常用方法。它将明文中的字母按照给的顺序安排在一个矩阵中,然后用根据密钥提供的顺序重新组合矩阵中字母,从而形成密文。例如,明文为attack begins at five,密钥为cipher,将明文按照每行6列的形式排在矩阵中,形成如下形式: a t t a c k b e g i n s a t f i v e 根据密钥cipher中各字母在字母表中出现的先后顺序,给定一个置换: 1 2 3 4 5 6 f = 1 4 5 3 2 6 根据上面的置换,将原有矩阵中的字母按照第1列,第4列,第5列,第3列,第2列,第6列的顺序排列,则有下面形式: a a c t t k b i n g e s a i v f t e 从而得到密文:aacttkbingesaivfte |
- package cn.hdu.edu.encrypt;
-
-
-
-
-
-
- public class Change {
-
- private final static int CRYPT_OK = 1;
- private final static int CRYPT_ERROR = 0;
-
-
-
-
-
- public static int encrypt(String initCode)throws Exception{
-
- StringBuilder sb = new StringBuilder();
-
-
- int codeLength = initCode.length();
-
- int rows = (int)Math.ceil(codeLength/6.0 );
-
-
- char[][] initChar = new char[rows][6];
-
- for(int i = 0; i < initChar.length; i++ )
- for(int j=0; j < initChar[0].length; j++){
-
- try{
- initChar[i][j] = initCode.charAt(
- (i ) * initChar[0].length + j
- );
- }catch(Exception e){
-
- initChar[i][j] = 64;
- }
- }
-
-
-
-
-
-
-
-
- char[][] targetChar = new char[rows][6];
- for(int i = 0; i < targetChar.length; i++ )
- for(int j=0; j < targetChar[0].length; j++){
-
- if(j == 1 ){
- targetChar[i][j] = initChar[i][3];
- }
-
- else if(j == 2){
- targetChar[i][j] = initChar[i][4];
- }
-
- else if(j == 3){
- targetChar[i][j] = initChar[i][2];
- }
-
- else if(j == 4){
- targetChar[i][j] = initChar[i][1];
- }
-
- else{
- targetChar[i][j] = initChar[i][j];
- }
- }
-
-
- for(int i = 0; i < targetChar.length; i++ )
- for(int j=0; j < targetChar[0].length; j++){
- sb.append(targetChar[i][j] );
- }
-
-
-
-
-
-
- String targetCode = sb.toString();
- System.out.println(targetCode);
- return CRYPT_OK;
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
- public static int decrypt(String targetCode)throws Exception{
-
-
- StringBuilder sb = new StringBuilder();
-
-
- int codeLength = targetCode.length();
-
- int rows = (int)Math.ceil(codeLength/6.0 );
-
-
- char[][] targetChar = new char[rows][6];
-
- for(int i = 0; i < targetChar.length; i++ )
- for(int j=0; j < targetChar[0].length; j++){
-
- targetChar[i][j] = targetCode.charAt(
- (i ) * targetChar[0].length + j
- );
- }
-
-
-
-
-
-
-
-
-
- char[][] initChar = new char[rows][6];
- for(int i = 0; i < initChar.length; i++ )
- for(int j=0; j < initChar[0].length; j++){
-
- if(j == 1 ){
- initChar[i][j] = targetChar[i][3];
- }
-
- else if(j == 2){
- initChar[i][j] = targetChar[i][4];
- }
-
- else if(j == 3){
- initChar[i][j] = targetChar[i][2];
- }
-
- else if(j == 4){
- initChar[i][j] = targetChar[i][1];
- }
-
- else{
- initChar[i][j] = targetChar[i][j];
- }
- }
-
-
-
-
- for(int i = 0; i < initChar.length; i++ )
- for(int j=0; j < initChar[0].length; j++){
- sb.append(initChar[i][j] );
- }
-
-
-
-
-
-
-
-
-
- String initCode = sb.toString();
- System.out.println(initCode);
- return CRYPT_OK;
- }
-
-
- }
本文转自 nileader 51CTO博客,原文链接:http://blog.51cto.com/nileader/298240,如需转载请自行联系原作者